0

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_encoded 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.

Community
  • 1
  • 1
threeFatCat
  • 840
  • 13
  • 30

1 Answers1

0

If I understand correctly, you're trying to distinguish whether data is an array or a single object? If so, I'd suggest checking this post.

Since you're using jQuery you can use isArray:

$.ajax({
    type:'POST',
    url: ,
    data:,
    dataType : 'json',
    success: function(data){
        console.log(data);
        if(data){
            if ($.isArray(data))
            {
                for (var i = 0; i < data.length; i++)
                    console.log(data[i]['SEND_FROM']);
            }

            else
                console.log(data['SEND_FROM']);
        }
    },
    error: function(jqXhr, textStatus, errorThrown){
        console.log(errorThrown);
        }
});
Community
  • 1
  • 1
Jimmy P
  • 1,790
  • 4
  • 17
  • 32
  • it's not really the direct answer that I needed but your `$.isArray` help me to find another way around. Thank you. – threeFatCat May 19 '17 at 22:35