Alon Shmiel
Alon Shmiel

Reputation: 7121

JSON.parse causes "Uncaught SyntaxError: Unexpected token u"

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?

Upvotes: 0

Views: 2107

Answers (2)

Michael Liu
Michael Liu

Reputation: 55339

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.

Upvotes: 4

milestyle
milestyle

Reputation: 931

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.

Upvotes: 0

Related Questions