Passing array via AJAX from php to javascript

I need to get an array created with script php. I have latitude and longitude for each user in the database. I am fetching values ​​from db with this code (file.php):

$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
    $array[]=$data['Latitude'];
    $array[]=$data['Longitude'];
}

echo $array;

      

and i am calling with ajax with this code:

$.post('./file.php',
     function( result ){    
         alert(result);
     });

      

but even if in script php the array is correct (if i echo array [25] i get correct value) in javascript i get "Undefined". How can I get the array correctly? thank!

edit: after encoding with json_encode ($ array); in php and JSON.parse (result) in javascript doesn't seem to work. In the console, I have an array, but I cannot access its values. (Array [0] gave me "Undefined").

+3


source to share


3 answers


use this

echo json_encode($array);

      

server side



and

var arr=JSON.parse(result);

      

client side

+18


source


As Ruslan Polutsyagan said, you use

echo json_encode($array);

      

on the PHP side.

On the Javascript side, you can simply add DataType to $ .post () - Function:

$.post(
  './file.php',
  function( result ){    
    console.log(result);
  },
  'json'
);

      



and the result-Parameter is the parsed JSON-Data.

You can also set the correct Content-Type in your PHP Script. Then jQuery should automatically parse the JSON data returned from your PHP script:

header('Content-type: application/json');

      

See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode

+1


source


You need to convert php array to json, try:

echo json_encode($array);

jQuery should be able to see the json return and automatically create the javascript object.

$.post('./file.php', function(result)
{    
     $.each(result, function()
     {
         console.log(this.Latitude + ":" + this.Longitude);
     });
});

      

0


source







All Articles