Reputation: 263
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?
Upvotes: 0
Views: 319
Reputation: 388406
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
Upvotes: 4