0

I'm trying to AJAX a JSON array but for some reason when I use JSON.parse it gives me the error: Uncaught SyntaxError: Unexpected token

Here is my PHP:

$infoJson = array('info' => array());
while($row = mysqli_fetch_array($query))
{
    array_push($infoJson['info'],
    [
        'section' => $row['section'],
        'source' => $row['source'],
        'project' => $row['project'],
        'client' => $row['client'],
        'date' => $row['date'],
        'id' => $row['id']
    ]);
}
echo json_encode($infoJson);

And here is the Javascript:

request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if(request.readyState == 4 && request.status == 200)
    {
        var response = request.responseText;
        response = JSON.parse(response);
    }
}
request.open('GET','http:edit.php?requestedArray=printArray',true);
request.send();

Also here is exactly what the PHP is echoing:

{"info":[{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/7\/7a\/SNES-Controller.jpg\/1280px-SNES-Controller.jpg","project":"SNES","client":"Nintendo","date":"1990","id":"7"},{"section":"printArray","source":"http:\/\/ecx.images-amazon.com\/images\/I\/81Q0l1t%2BaJL._SL1500_.jpg","project":"Playstation","client":"Sony","date":"1994","id":"8"},{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/e\/ed\/Xbox-360-S-Controller.png","project":"Xbox 360","client":"Microsoft","date":"2005","id":"9"}]}

If I don't use JSON.parse and console.log response, I do receive it as a string.

2
  • Are you using jQuery at all, I usually just do $.post, you could try sending header('Content-Type: application/json'); but I'm not sure if that would have any effect. Commented Jul 11, 2014 at 23:59
  • possible duplicate of JSON.parse throwing illogical Syntax Error: Unexpected token Commented Jul 12, 2014 at 0:06

1 Answer 1

4

Your output parses fine, except for the invalid, invisible character '\ufeff' at the beginning of the string. This is the UTF-16 byte order mark. You are probably sending the string with an incorrect/missing charset in your Content-Type header.

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

3 Comments

Just out of curiosity how do you tell that?
Triple-click the text in the question, paste it into the JavaScript console: var s = '<paste>'; s.charCodeAt(0); /* 65279 */ JSON.parse(s); /* Unexpected token */ JSON.parse(s.substr(1)); /* Object { info: Array[3] } */
Whats the fix ?

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.