I have seen a bunch of different ways to call a php script via ajax that returns json but i cant seem to get any working I was curious if someone could help me.
Here is my PHP script:
//database connection stuff....
$query = "SELECT * FROM weather limit 10";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
// get data and store in a json array
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$orders[] = array(
'zip' => $row['zip'],
'temp' => $row['temp'],
'time' => $row['time']
);
}
echo json_encode($orders);
Next here is my ajax call:
$.ajax({
url : 'getweather.php',
type : 'post',
dataType: 'json',
success: function(data){
for (var x = 0; x < data.length; x++) {
alert(data['zip']);
}
}
});
});
With this i just get 10 alerts that say undefined. Can someone please help me figure out what i am doing wrong?
Thanks in advance for the help!
Craig
asked Sep 28, 2015 at 23:01
1 Answer 1
Your data
is an array of arrays, you need to index the outer array before the inner array:
alert(data[x]['zip'])
answered Sep 28, 2015 at 23:05
1 Comment
craigtb
i knew it'd be something simple. Thanks!
default
data[x]['zip']