1

I'm sending an AJAX post request to a php script on my server, the server returns the data in JSON format. When I try and alert the results I get the following error: Uncaught SyntaxError: unexpected token { twice.

Here is my AJAX call:

var articles = $.post("process/get_articles.php"); articles.done(function(data){ var result = $.parseJSON(data); alert(result); }); 

My server side code:

while($query->fetch()){ $result = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link); $result = json_encode($result); echo $result; } 

which returns the following:

{"ID":1,"Article":"Article 1","Image":"http:\/\/wwww.mydomain.com\/images\/img.jpg"}{"ID":2,"Article":"Article2","Image":""}{"ID":3,"Article":"Article 3","Image":""} 

Why is the data returned not properly alerted? Any help is greatly appreciated!

1
  • 2
    Your JSON is invalid. Run it through jsonlint.com Commented Apr 12, 2015 at 14:15

4 Answers 4

7

You're echoing the JSON strings inside a loop, and you end up with a long invalid string made up of shorter JSON strings.

You have to encode and echo it once

$result = array(); while($query->fetch()){ $result[] = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link); } echo json_encode($result); 
Sign up to request clarification or add additional context in comments.

Comments

3

Your code is spitting out successive JSON objects back-to-back. The result, overall, is not valid JSON.

Put your arrays in an enclosing single array and then JSON-encode that as the response. That'll result in the client getting an array of objects, which will be valid.

Comments

1
$array = array(); while($query->fetch()) $array[] = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link); echo json_encode($array); 

Comments

0

More objects just one after the other are not valid JSON. Your parser complains about the start of the second object, which is completely OK. Wrap the objects into an array and it should work.

Comments