How to get multiple responses from a single AJAX call (jQuery, JSON and PHP)
I keep getting questions on my email from web developers wanting to receive two responses in a single ajax request. While I do have a piece of content written about this (which suggests using a suitably rare delimiter to split out the different responses), because this was done so long ago, the obvious (and common) answer now is JSON.
JSON has been around for years and is one of the most commonly used data transport frameworks/methods. It's theoretically similar to the backwards method I covered in that old 2007 blog post, but it's more durable.
What is JSON?
You can read the overly technical definition if you like but if (like me) you only care about how to use it (rather than how it came to be) then maybe the Wikipedia page is a better option.
In essence, it's a means of serialising a response within a string which can easily be pulled apart into an object at either end after transmit. An example of this is below:
Okay, so how can I use this?
Excuse if there are any inaccuracies, I've quickly written this example of how you'd make an AJAX request in jQuery to return JSON. Check jQuery's AJAX documentation, my code below has been hand-written and not checked, so it's for demonstration purposes only.
The above script would make an AJAX request to myscript.php which expects a JSON response.
In the PHP script (in addition to any handling of the data sent to you via the script) you will want to output a JSON string. The easiest way to do this is using a specific function:
The beauty of the json_encode function is that it can take any kind of input and convert it into a JSON string. The most preferable input would be an associative array for obvious reasons, but it'll take whatever you give it (apart from a resource). Echoing it out means that it'll be your AJAX response.
Then you just need to call the parseJSON jQuery function to turn it into an object to manipulate.
Multiple responses from a single AJAX call:
Be creative. If your myscript.php needs to return two entirely different sets of data, just bung the entire response into an associative array and let the JSON encoding deal with it.
While I'm sure this isn't a best practice approach, sometimes you need to write something scaleable and therefore reduce the amount of requests made, in which case this isn't a bad idea. Certainly better than the old blog post I have on this site.
So, hopefully this helps someone somewhere who doesn't understand how JSON can overcome the problem of needing multiple responses from a single AJAX call.
Enjoy this article? Why not subscribe to the full RSS feed?


