TaneMahuta
TaneMahuta

Reputation: 377

jQuery / Ajax: How to loop through array as part of Ajax success function

I have an Ajax call that returns an array and need to do something with each of the values from this array.

So far I have the below but this returns the following error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in array(5)...

Can someone tell me what I am doing wrong here resp. how I can do something with each of the values ?

My Ajax:

$.ajax({        
    type: "post",   
    url: "ajax.php",
    cache: "false",
    data: {
        node: 'fetchValues',
        itemIDs: itemIDs
    },
    success: function(data){
        console.log(data);  // for testing only
        jQuery.each(data, function(index, value){
            console.log(value);
        });
    }
});

Example for "data" (from console log):

array(5) {
  [1]=>
  string(6) "Value1"
  [2]=>
  string(6) "Value2"
  [3]=>
  string(6) "Value3"
  [4]=>
  string(6) "Value4"
  [5]=>
  string(6) "Value5"
}

Many thanks in advance for any help.

Upvotes: 3

Views: 22129

Answers (2)

Anto S
Anto S

Reputation: 2449

seems like your array not parsed properly

from php side before sending response

echo json_encode($result); // REPLACE $result WITH  YOUR OUTPUT ARRAY

On jquery side:

$.ajax({        
    type: "post",   
    url: "ajax.php",
    dataType : 'JSON',
    cache: "false",
    data: {
        node: 'fetchValues',
        itemIDs: itemIDs
    },
    success: function(data){
        console.log(data);  // for testing only
       var data=$.parseJSON(data);
        jQuery.each(data, function(index, value){
            console.log(value);
        });
    }
});

Ref: http://api.jquery.com/jquery.parsejson/

Upvotes: 5

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

You need to parse the string in your data variable to an object:

success: function(data){
    console.log(data);  // for testing only
    var res=$.parseJSON(data);
    jQuery.each(res, function(index, value){
        console.log(value);
    });
}

You can either use

var res=$.parseJSON(data)

Or plain JS:

var res=JSON.parse(data)

Source

Upvotes: 1

Related Questions