I've been reading this, this, this until I reached this.
Basically what I'm trying to do is just iterate the data returned from an Ajax call which is json_encode
d in the php side.
This is the structure of the object that returned when I use console.log(data)
:
Object {0: "218", 1: "SCT_22156", 2: "10456", 3: "S5_MAN_Artwork-Processing", 4: "Duma Guete", ID: "218", ARTICLE_ID: "SCT_22156", METADATA_ID: "10456", FROM_STAGE: "S5_MAN_Artwork-Processing", SEND_FROM: "Duma Guete"}
What I use to iterate is this (I would like to get each value from each key, so example I would like to get the metadata_id
):
$.each(data, function( k, v ) {
console.log(v.METADATA_ID);
});
But this returns undefined
.
Note: During ajax call data returned maybe one or more object.
What I noticed, it doesn't return undefined
when the data returned is more than one object, thus making it JSONArray. So if the data returned is like this:
Object [{"data":"value"..},{"data":"value"..}]
$.each
works fine.
Is there anyway that I can specifically tell the server side (php
) should return JSONArray even it contains one object only?
I tried using for in loop
too, but in reverse it doesn't work with JSONArray. I tried adding timeouts
too, but no luck. What am I doing wrong here?
This is my ajax call:
$.ajax({
type:'POST',
url: ,
data:,
dataType : 'json',
success: function(data){
console.log(data);
if(data){
$.each(data, function( k, v ) {
console.log(v.SEND_FROM);
});
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
I tried using this trick:
$.each([data], function( k, v ) {
console.log(v.METADATA_ID);
});
Adding brackets,but it will cause undefined
for JSONArray(multiple object) result.