Question:
Ajax, returning multiple values from PHP script?
anonymous
2009-07-24 10:15:28 UTC
I am currently building a search application and I was wondering if anyone had any good ideas on how to return various values from a PHP script through to Javascript using Ajax. Currently I have no problem returning an array from php to javascript with Ajax, but can anyone suggust how i could return multiple arrays?
Three answers:
flybishop
2009-07-24 10:29:29 UTC
You can only ever return one thing at a time. When you return an array of values, you're not really return all of the values, you're returning 1 array. You could therefore return an array of arrays or you could return a serialized string from PHP and unserialize it in javascript then you have full access to everything no matter what datatype it was before the serialize.



To do that in PHP write: return serialize($returnarray);



This turns all of your $return value in to a giant string with the values and lengths and types for each item.



Then in Javascript use the Javascript Library from here http://www.phpguru.org/static/PHP_Unserialize.html to output it back to the original types.
kindom_2006
2009-07-24 10:27:09 UTC
If you can return arrays, then you can return multiple arrays, just make the array you return contain the other arrays ... ie.



where your old code sent $answer array (probably via JSON ... but doesn't matter how really).



and $answer looked like



$answer = array ( 'my first word', 'my second word' );



then use this instead:



$answer = array ( array ( 'first answer first word', 'first answer second word' )

, array ( 'second answer first word', 'second answer second word ' )

, );



======



if on the other hand your answer was associative, even easier:



where before you had:



$answer = array ( 'part1'=>37, 'name'=>'Johny' );



You can use:



$answer = array ( 'answer1'=>array ( 'part1'=>3, 'name'=>'Johny' )

, 'answer2'=>array ( 'part1'=>14, 'name'=>'Suzie' )

, );



Hope that helps
neubecker
2016-10-30 04:38:14 UTC
Loading...