Return Multiple Values from AJAX script with ease
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.
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.
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 -
Now,we’re gonna encode this data as JSON object. For that,
Now your array will look like -
Initialize a variable to store the returned string in it -
Now we need to transform this JSONText to a JSON Object. For that, we can use the eval() function. Like-
both works the same in this case. So now that we have a JSON Object, lets get those data.
And that’s it, you’ve got your data back. :)