0

I have a problem with parsing the json string passed from a method in PHP over an AJAX call. The string is

[{"type":"successful","message":"Prijava uspe\u0161na!"}] 

When I try to parse it in javascript with JSON.parse(the string), I get an Unexpected token error in my console.

There is no problem when I execute this on my localhost nothing is wrong even though I get the same response from the PHP script.

When I try the following in the success function of the ajax

console.log(message);
console.log(JSON.stringify(message));
console.log(JSON.parse(message));

I get this

[{"type":"successful","message":"Prijava uspe\u0161na!"}]  login:102
"\r\n\r\n[{\"type\":\"successful\",\"message\":\"Prijava uspe\\u0161na!\"}]\r\n\r\n" login:104
Uncaught SyntaxError: Unexpected token  login:104

And line 104 (well not really, the console points at it):

console.log(JSON.parse(message));

I've tried replacing \r\n, ended up the same

I am really confused...

3
  • Your JSON parses fine. JSON.parse('[{"type":"successful","message":"Prijava uspe\\u0161na!"}] '); Commented Apr 8, 2014 at 16:14
  • maybe he passed the object instead of the string (without the quotes) Commented Apr 8, 2014 at 16:15
  • @Brad Yes I am aware of that, but it does not when it's passed from a php echo Commented Apr 8, 2014 at 16:41

1 Answer 1

1

Your JSON has a BOM, which is not a valid token.

Ensure that whatever is sending your JSON is encoding it correctly without this BOM.

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

3 Comments

Could you please explain? The PHP method echos the array with json_encode
If your PHP script is encoded as UTF-8 with BOM, then the BOM is output. Encode your PHP script as either ANSI (a single-byte character set) or UTF-8 without BOM.
Hehe, one thing you learn to recognise is "invisible errors" :D

Your Answer

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