0

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?

4 Answers 4

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

2 Comments

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

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();

2 Comments

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.
Steven: it's prototype in my example, but your choice depends on your needs. jQuery is very popular nowadays.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.