0

I'm trying to read the data sent back to my ajax request from the server. I echo back an array then I want to read each value and place it on the desired place on the page. I'm not sure how to work with the JSON that was sent back. The example I looked at seemed to say I just needed to reference it like an array, but that doesn't work.

//AJAX Request
$.post("getData.php", {trackingNum: trackNum},
function(result) {
    alert(result);
    usrID(result[0]);
    setTracking(result[1]);
    carType(result[2]);
    status(result[3]);
});

//PHP
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $array[0] = $row[0];
    $array[1] = $row[1];
    $array[2] = $row[2];
    $array[3] = $row[3];
}
echo json_encode($array);

What I'm getting back from the alert looks like this: ["2","D78A19C","Nissan","Sanding"] But it won't reference like an array. Help?

3
  • json_encode is going to encode the string as JSON... What does the data actually look like prior to encoding? Commented May 22, 2013 at 13:55
  • You should use proper keys, not just an array of strings. Commented May 22, 2013 at 13:57
  • I would recommend to use some meaningful keywords in the array. For instance: $array['username'] = $row[..] and then in your js code you could use it that way: result.username (object). Which is much more semantically correct than result[0] Commented May 22, 2013 at 13:59

1 Answer 1

1

you need to specify that return data is type of JSON.

use $.getJSON instead of $.post or just use

 $.ajax({
     type: 'post',
     url: "getData.php", 
     data: {trackingNum: trackNum},
     dataType: 'json',
     success: function(result) {
         alert(result);
         usrID(result[0]);
         setTracking(result[1]);
         carType(result[2]);
         status(result[3]);
     }
 });

Tip: get rid of mysql_* functions and instead use mysqli or PDO.

Sign up to request clarification or add additional context in comments.

1 Comment

Unless he wants to make a post, just look at api.jquery.com/jQuery.post and search for json. Great example

Your Answer

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.