How to return multiple JSON objects from PHP to jquery with AJAX

Returning a single object from PHP with JSON is pretty easy. You can have, say, a user in a database and echo it with the following result:

{“id”:”1″,”name”:”me”}

But what if you want to return more users (say, all of them?). Then you could echo all the users in the same way, which would look like this:

{“id”:”1″,”name”:”me”}

{“id”:”2″,”name”:”you”}

{“id”:”3″,”name”:”them”}

which is a problem, because you cannot simply access it like this anymore:


$.ajax({
type: "POST",
url: "adminGetUsers.php",
data: "",
dataType: "json",
success: function(results){
alert(results.name);
alert(results[0].name);
//neither of these work
}
});

view raw

script.js

hosted with ❤ by GitHub

Instead, what you should do is to make a new JSON object with a single value, which is an array of all the users. This would then look like this:

{“Users”:”[

{“id”:”1″,”name”:”me”},

{“id”:”2″,”name”:”you”},

{“id”:”3″,”name”:”them”}

]”}

The PHP code to do this is as follows:


<?php
$result = query("SELECT * FROM Users");
//your query will probably look different
$array = array (
'Users' => array (),
);
$i = 0;
while ($row = mysqli_fetch_array($result))
$array['Users'][$i++] = $row;
$json = json_encode($array);
echo $json;
?>

view raw

query.php

hosted with ❤ by GitHub

Now you can access the data in the jQuery like so:


$.ajax({
type: "POST",
url: "getUsers.php",
data: "",
dataType: "json",
success: function(results){
$.each(results['Users'], function(key, val) {
$('body').append('<div>' + val.id + ' ' + val.name + '</div>');
});
}
});

view raw

script.js

hosted with ❤ by GitHub

(PS: I also made another post relating to this problem: How to return multiple JSON objects from PHP to jquery with AJAX part 2)

8 thoughts on “How to return multiple JSON objects from PHP to jquery with AJAX

      1. I mean, a user gets informed with the progress of the process in php file. To do that I think php file should send multiple response objects over time. Any clue on how to do that?

      2. If I’m understanding you correctly, you would (as far as I know) have to use separate ajax requests to get the results for each individual record. (So, for each record you want to retrieve, you would use a separate $.ajax function.)

        This way you could keep track of how many records have been retrieved, etc. although this method would be a lot slower, because you’re sending a lot of ajax requests.

        Does this answer your question?

Leave a reply to SutoCom Cancel reply