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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getUsers(){ | |
| return $.ajax({ | |
| type: “POST”, | |
| url: “getUsers.php”, | |
| data: “”, | |
| dataType: ‘json’, | |
| async:’false’, | |
| success: function(results){ | |
| } | |
| }).responseText; | |
| } |
Then you could use it like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
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”