It seemed that from time to time, we ran into this error “Uncaught SyntaxError: Unexpected token o“. Without more specific info, sometimes this can be very frustrating.
As matter of fact, this error was simply a result of sloppy coding in creating a JSON string that was not parsed correctly. Tracked down to the piece of code where error was thrown – it occurred where JSON.Parse was called. If the string s passed into the JSON.Parse(s) is not properly formatted JSON string, the above error is thrown. In the sample code snipe below, r is a json string returned from a AJAX call from C# code; if I called JSON.parse(r), I would get the “Uncaught SyntaxError: Unexpected token o” error; and if r is not properly formatted, I also got the same error. Correct way to parse the returned json string is to call JSON.parse(r.d), instead of JSON.parse(r). I also tried to call JSON.parse(r.responseText), as it worked with the the xhr returned in the error function, but I got a different error, “Uncaught SyntaxError: Unexpected token u“, very interesting. Only r.d worked! Who came up with such super terse object name?!!
function fetchEmployer(code) { var account = null; var url = "<%=AjaxPath%>/GetEmployer"; var json = JSON.stringify({EmployerCode: code}); $.ajax({ type: "POST", url: url, data: json, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function (r) { account= JSON.parse(r.d); //the error will be thrown if you just parse r instead of r.d //alert(r.d); }, error: function (xhr, ajaxOptions, thrownError) { if (xhr != null) { var err = JSON.parse(xhr.responseText); //you can throw a code-behinde Exception and it will automatically //render to a valid JSON string when we rerieve the responseText alert("ErrorMessage: " + err.Message + " StackTrace: " + err.StackTrace); } } }); return account; }