Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
json_encode is going to encode the string as JSON... What does the data actually look like prior to encoding? –  brbcoding May 22 '13 at 13:55
    
You should use proper keys, not just an array of strings. –  moonwave99 May 22 '13 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] –  Ofir Baruch May 22 '13 at 13:59

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Unless he wants to make a post, just look at api.jquery.com/jQuery.post and search for json. Great example –  Hendriq May 22 '13 at 13:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.