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

In a previous post (https://diffiebosman.wordpress.com/2012/09/30/how-to-return-multiple-json-objects-from-php-to-jquery-with-ajax/), I explained how to, well, return multiple JSON objects from PHP to jQuery with AJAX. In my approach I worked directly with the returned results in the jQuery.ajax function. Another approach is to write a function that returns a stringified version of the results in jQuery.

(Refer to the previous post for the PHP-code)

The JavaScript would now look something like this:


function getUsers(){
return $.ajax({
type: “POST”,
url: “getUsers.php”,
data: “”,
dataType: ‘json’,
async:’false’,
success: function(results){
}
}).responseText;
}

view raw

script.js

hosted with ❤ by GitHub

Then you could use it like this:


var users = getUsers();
users = JSON.parse(users); //turn it into a js-object
for(i in users.Users){
$(‘ul#usersList’).append("<li>"+users.Users[i].name+"</li>");
// you can now access different member variables in the object with users.Users[i].memberVariable
}

view raw

script.js

hosted with ❤ by GitHub

I like this approach better (than the first), because then you have a central function that you can always use over and over (with only a few lines of code).

One thought on “How to return multiple JSON objects from PHP to jquery with AJAX part 2

Leave a comment