Return Multiple Values from AJAX script with ease

· 1 min read


This post is not for Expert users. Only the novice guys who are interested in these stuff, might have a look.

While working on an AJAX implemented script, we sometimes need to return a lot of data from the server side script. If you've worked with AJAX, you'll know that the script returns the value as httpObject.responseText. And the value of responseText is what you echo from your script. Now that makes our scope limited. Assuming that We have a javascript file testAjaxJs.js and testAjaxPhp.php .. If you try to make a lot of echo inside the php script, all of them are gonna get appended one behind another and appear like, for an example, this - BibhasChandraDebnath. Now, you may have an idea of echoing a special character like '-' or '_' after each echo so that you can then split the whole text inside the JS file using the split function and form an array. That might be an idea, but there is a better way. Why not just use JSON to return data as array? Well, PHP can pretty much deal with JSON and it is a native thing to Javascript. So, it becomes easier. :) Do this, initialize an array inside the php script, and whenever you have a data ready to be returned, insert it into the array. So at the end of the script, you'll have an array like this -
    [first_name] => Bibhas
    [middle_name] => Chandra
    [last_name] => Debnath
Now,we're gonna encode this data as JSON object. For that,
Now your array will look like -
As this is a string to PHP, you can easily echo it. Now lets go to the Javascript part to read this JSON string we just sent to it. Initialize a variable to store the returned string in it -
var jsonText = httpObject.responseText
Now we need to transform this JSONText to a JSON Object. For that, we can use the eval() function. Like-
var jsonObject= eval('('+jsonText+')');
both works the same in this case. So now that we have a JSON Object, lets get those data.
var firstName=jsonObject.first_name;
var middleName=jsonObject.middle_name;
var lastName=jsonObject.last_name;
And that's it, you've got your data back. :)