I've been trying to figure out how to do this -- I want to pass an array(array()) from PHP to jQuery. I've done it before with a single array but never with a nested array.
Here is my PHP code:
$sector_one = array('one' => 0, 'two' => 1, 'three' => 0, 'four' => 0);
$sector_two = array('one' => 0, 'two' => 1, 'three' => 0, 'four' => 0);
$sector_three = array('one' => 0, 'two' => 1, 'three' => 0, 'four' => 0);
$sector_four = array('one' => 0, 'two' => 1, 'three' => 0, 'four' => 0);
$array = [];
$array[0] = $sector_one;
$array[1] = $sector_two;
$array[2] = $sector_three;
$array[3] = $sector_four;
Now -- I haven't the slighest idea how to handle the data aspect of this once it's past to jquery. How would I go about accessing the information in $array[0]['one'] in jquery?
Simply encode it using json_encode
echo json_encode($array);
And to get it back in jQuery
var array = jQuery.parseJSON(response);
// You can grab particular data like so:
console.log(array[0].one);
You need to convert this array to JSON and then return it to AJAX. Something like this:
return json_encode($array);
Then in the front end you'll be able to treat the data as a JavaScript array.
It has been a while but I think something like the following should work in your AJAX (assuming the success variable is called data
):
var array = $.parseJSON(data);