0

In PHP file, I have the following concept:

// return assoc
$res = DBQUERY;
foreach ($res as $key => $value) {
$retval[$cnt] = array("id_enumeration" => $key, "display_value" => $value);
$cnt++;
}
echo json_encode($retval);

In success result I got in Firebug array of objects like this:

[ {"id_enumeration": 3602, "display_value": "Test1"}, {"id_enumeration": 3604, "display_value": "Test2"}, {"id_enumeration": 3605, "display_value": "Test3"}, {"id_enumeration": 3607, "display_value": "Test4"}, {"id_enumeration": 3610, "display_value": "Test5"} ]

I'm trying to perform this code by foreaching:

success: function(data) {
   // get array:
   $.each(data, function(idx, obj) { 
      // get each object:
      $.each(obj, function(key, value) {    
         console.log("Display value: " + value.display_value + " ID enumeration: " + value.id_enumeration);                             
      });
   });
}

But variables in console.log are undefined. How to each much objects in array? What is the best way to do that?

1 Answer 1

4

You have obj which is an array of objects which has the display_value property, so you can access it via obj.display_value in the first $.each() loop, there is no need for the second one

   $.each(data, function(idx, obj) { 
      console.log("Display value: " + obj.display_value + " ID enumeration: " + obj.id_enumeration);                             
   });

Demo: Fiddle

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

2 Comments

$.each(data, function(idx, obj) { console.log("Display value: " + obj.display_value + " ID enumeration: " + obj.id_enumeration); }); Still undefined.
Works now... My mistake, forgotten dataType: "json".

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.