2

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
  • You are not using your x. Try data[x]['zip'] Commented Sep 28, 2015 at 23:04

1 Answer 1

2

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

i knew it'd be something simple. Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.