0

I have:

<input type="hidden" id="notifications" value="@ViewBag.Notifications" />

When I put a breakpoint on this line and check the value, I see that the value is:

[{"id":"42647","isRead":0,"MessageType":3},{"id":"fsh3hg","isRead":0,"MessageType":2}]

I want to parse this value in JavaScript when the page loads, so I wrote:

var notifications = document.getElementById('notifications').value;
alert(notifications); // it prints undefined
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement

var parsedNotifications;

if (notifications != '') {
    parsedNotifications = JSON.parse(notifications);
}

but I get the error "Uncaught SyntaxError: Unexpected token u" on the following line:

parsedNotifications = JSON.parse(notifications);

Why does this error occur?

5
  • undefined is not valid JSON. What's the generated source? Commented Jul 23, 2013 at 18:23
  • it's a list of a class.. Commented Jul 23, 2013 at 18:24
  • The value is not being output correctly. here is a fiddle with the value correct and it is working: jsfiddle.net/A5Kf7 Commented Jul 23, 2013 at 18:26
  • you are doing some mistake while parsing...this error mostly appears when we use json.parse with an undefined object... Commented Jul 23, 2013 at 18:26
  • did you try using $.parseJSON(notifications) ? Commented Jul 23, 2013 at 18:28

2 Answers 2

4

You wrote:

alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement

In the comment, HtmlSpanElement is a clue that something's wrong. Apparently, your page has a <span> whose id is the same as that of your hidden <input>, so document.getElementById finds the wrong element, and value returns undefined because a <span> doesn't have a value.

Change the id of the <span> to something other than "notifications", and your code should work.

Sign up to request clarification or add additional context in comments.

Comments

0

So we know that document.getElementById('notifications') is there, which means that the only problem is it can't find the input value. Sometimes external libraries will block the input of hidden elements. Strip your page of everything except for the the code you showed us, and then try adding in the other libraries you've included one-by-one till you find the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.