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

18,703

Solution 1

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/

Solution 2

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

Share:
18,703
TaneMahuta
Author by

TaneMahuta

Updated on June 04, 2022

Comments

  • TaneMahuta
    TaneMahuta almost 2 years

    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.