Hris Hris - 9 months ago 59
Javascript Question

Save AJAX responses in Arrays

I'm having X and Y coordinates in my MySQL table. I have them in my php file putting them in an associative array

echo $row['x'];
echo $row['y'];

I want to save them in my html file ( with javascript) in 2 Arrays.
How is this possible? Can I use for example a javascript loop which switches from saving the output (the x and y coordinates) in different arrays?

Thanks for every response!


Put them into a PHP array, then convert that to Javascript using json_encode.

$array = array();
    $array[] = array('x' => $row['x'], 'y' => $row['y']);
echo json_encode($array);

In the Javascript, the AJAX callback function can use JSON.parse() to convert this to an array of objects.

If you want two arrays, push the x and y values onto different arrays, then combine them in the JSON response.

$xarray = array();
$yarray = array();
    $xarray[] = $row['x'];
    $yarray[] = $row['y'];
echo json_encode(array('x' => $xarray, 'y' => $yarray));

Then in the Javascript you do:

var obj = JSON.parse(response);
var xarray = obj.x;
var yarray = obj.y;