1

I want to get the value of json array using .each

here's where I set the values of array

$allRecords= array();
    while($row = mysql_fetch_array($result)){
        $oneRecord[] = array("orderNo"=>$row['order_no'],"orderDate"=>$row['order_date'],"orderTime"=>$row['order_Time']);
        array_push(&$allRecords,$oneRecord);
    }

    echo json_encode($allRecords);

and here's what I make in jquery

$.post("controllers/OrderViewer.controller.php?action=viewOrders",param,function(result){
 // var data = JSON.parse(result); // I tried this but doesn't work
 // var data= eval(result);  // I tried this but doesn't work

    $.each(result,function(index,v){

            alert(index +" "+ v.orderNo);  // return undefined for values
            // what should I write here to reach array element

    });
    });

what should I write in .each to get array elements

here's the response data structure

Array
(
[0] => Array
    (
        [orderNo] => 1
        [orderDate] => 2011-02-12
        [orderTime] => 00:00:10
    )

[1] => Array
    (
        [orderNo] => 2
        [orderDate] => 2011-02-12
        [orderTime] => 11:10:00
    )

)

3
  • Just do a console.log( data ) and take a look at the structure of your data object. Commented Sep 9, 2011 at 19:43
  • It's probably worth stripping down your example to just the $.each call with a JavaScript array of objects assigned to the result variable. You can examine what's coming back from your php page to see what that should look at. At that point, it's purely a JavaScript problem. As for what to put into your $.each function, you can try result[index].orderNo. Commented Sep 9, 2011 at 19:48
  • 1
    I believe your jquery AJAX call will receive a string from the PHP script. you need to do var data = eval(result), and then try iterating over data, not result. Commented Sep 9, 2011 at 19:53

1 Answer 1

2

If index and v are returning undefined values in your each() loop, then the value of result must not be what you think it is. The only way to make progress here is for you to see what result actually looks like.

Is it actually an array? If so, what are the items in the array? Are they what you expect? If it's not an array, what is it?

The best way to see result is to set a breakpoint on the start of your each() loop and look at result in the debugger. Chrome and Safari come with built-in debuggers that take 15 mins to learn how to set a breakpoint and then inspect the values of variables once it hits that breakpiont. Firefox has a free add-on (Firebug) that gives it a debugger too. IE has tools you can download from MS with a debugger.

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

Comments

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.