tags:

views:

207

answers:

4

I am using AJAX to fetch a multidimensional array, so a multidimensional array is returned to AJAX, how can I deal with the data with AJAX? I need to read all values in the multidimensional array. I use the following code to return the array to AJAX.

$resultset=array();
while($row=mysql_fetch_assoc($result))
{
    $resultset[]=$row;
}
print_r($resultset);

How to read all values in an array returned by a PHP file using AJAX?

A: 

I would personally use JSON for that. E.g. in php instead of print_r use json_encode($resultset). And in javascript use some JSON-supporting lib (jquery/mootools will do) to decode JSON. That is it.

Jefim
+1  A: 

PHP

echo json_encode($resultset);

JS:

var array = json_decode(input);

json_decode in javascript is not supported by default, you might use a framework to implement this functionality. E.g: in prototype:

var array = input.evalJSON();
erenon
it would be most helpful if downvotes were commented. now I don't know which part of the answer is regarded as wrong by someone.
tharkun
What framework can I use?
Steven
Steven: it's prototype in my example, but your choice depends on your needs. jQuery is very popular nowadays.
erenon
+3  A: 

While it is possible to parse the output of print_r in JavaScript, it would be rather silly to do so when robust libraries for other data formats already exist for both languages.

Use JSON (links at the bottom of the page will take you to libraries for generating it in PHP and reading it in JavaScript).

David Dorward
jQuery has a nice built-in function that looks like this: `$.getJSON(url, data, callback)`. Details and example at api.jquery.com.
Nathan Long
+2  A: 

Yes, you can use JSON (JavaScript Object Notation) to transfer data across multiple platforms. If your data looks like:

<?php
  $a = array( );
  $a[ "foo" ] = array( );
  $a[ "bar" ] = array( );
  $a[ "foo" ][ "foo-1" ] = 1;
  $a[ "foo" ][ "foo-2" ] = 2;
  $a[ "foo" ][ "foo-3" ] = 3;
  $a[ "foo" ][ "foo-4" ] = array( "yada", "yada" );
  $a[ "bar" ][ "bar-1" ] = 1;
  $a[ "bar" ][ "bar-2" ] = 2;
  $a[ "bar" ][ "bar-3" ] = 3;
  $a[ "bar" ][ "bar-4" ] = array( "blah", "blah" );
?>

Then its json_encode( $a ) will return:

{"foo":{"foo-1":1,"foo-2":2,"foo-3":3,"foo-4":["yada","yada"]},"bar":{"bar-1":1,"bar-2":2,"bar-3":3,"bar-4":["blah","blah"]}}

You can use the JavaScript's eval function to convert this string into an object and the iterate it just like you would iterate a php array.

Salman A
+1 for showing how JSON looks. As David Dorward noted, www.json.org is a good resource and explains the structure in more detail.
Nathan Long
If anyone knows what (), [] and {} mean in JavaScript, learning JSON should be a piece of cake!
Salman A