161

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});
Tomalak
  • 332,285
  • 67
  • 532
  • 628
aherrick
  • 19,799
  • 33
  • 112
  • 188

12 Answers12

272

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

Thalis K.
  • 7,363
  • 6
  • 39
  • 54
cletus
  • 616,129
  • 168
  • 910
  • 942
  • The first loop is for a "category" while a loop within that is for an "attribute." How else is that done? – dcolumbus Oct 22 '10 at 16:03
  • What if you want to work with the object element rather than its properties? Why doesn't @aherrick's loop in the question work? – StuperUser Nov 04 '10 at 11:54
  • 1
    If this looping is used in a separate function use `$(data)` instead of `data`, otherwise the variable `k` always returns 0. – user1226868 Oct 17 '12 at 18:16
  • 2
    Could someone explain the variables k & v that are passed to the second function? – Brent Connor Mar 06 '15 at 19:08
  • @BrentConnor in this case k&v represent the key & value of the array being cycled through. Read up on jquery .each() function – Ghost Echo Apr 10 '15 at 15:51
  • 1
    I get this error: `Uncaught TypeError: Cannot use 'in' operator to search for '188' in` – Si8 Mar 17 '17 at 16:20
84

You can also use the getJSON function:

    $.getJSON('/your/script.php', function(data) {
        $.each(data, function(index) {
            alert(data[index].TEST1);
            alert(data[index].TEST2);
        });
    });

This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
clone45
  • 8,952
  • 6
  • 35
  • 43
  • This helped. For some reason I couldn't get @cletus 's answer to work but this did. Not sure what the grand mystery about jQuery is but simple code does not always work as you expect it to. – AturSams Jul 03 '14 at 04:48
42

If you use Fire Fox, just open up a console (use F12 key) and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

Shashanth
  • 4,995
  • 7
  • 41
  • 51
0100110010101
  • 6,469
  • 5
  • 33
  • 38
19

For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.

You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.

jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    data: data, 
    dataType: 'json', // ** ensure you add this line **
    success: function(data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
        });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});
Dave Hilditch
  • 5,299
  • 4
  • 27
  • 35
15

Access the json array like you would any other array.

for(var i =0;i < itemData.length-1;i++)
{
  var item = itemData[i];
  alert(item.Test1 + item.Test2 + item.Test3);
}
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
5

This is what I came up with to easily view all data values:

var dataItems = "";
$.each(data, function (index, itemData) {
    dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
Yovav
  • 2,557
  • 2
  • 32
  • 53
4

Try jQuery.map function, works pretty well with maps.

var mapArray = {
  "lastName": "Last Name cannot be null!",
  "email": "Email cannot be null!",
  "firstName": "First Name cannot be null!"
};

$.map(mapArray, function(val, key) {
  alert("Value is :" + val);
  alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
PanwarS87
  • 319
  • 5
  • 14
2

if you don't want alert, that is u want html, then do this

...
    $.each(data, function(index) {
        $("#pr_result").append(data[index].dbcolumn);
    });
...

NOTE: use "append" not "html" else the last result is what you will be seeing on your html view

then your html code should look like this

...
<div id="pr_result"></div>
...

You can also style (add class) the div in the jquery before it renders as html

The Billionaire Guy
  • 3,382
  • 28
  • 31
2

I use .map for foreach. For example

success: function(data) {
  let dataItems = JSON.parse(data)
  dataItems = dataItems.map((item) => {
    return $(`<article>
                <h2>${item.post_title}</h2>
                <p>${item.post_excerpt}</p>
              </article>`)
  })
},
Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
dimitar
  • 1,019
  • 13
  • 19
1

If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.

$.get('url', function(data, statusText, xheader){
 // your code within the success callback
  var data = $.parseJSON(data);
  $.each(data, function(i){
         console.log(data[i]);
      })
})
Frederick Eze
  • 121
  • 1
  • 12
1

I am partial to ES2015 arrow function for finding values in an array

const result = data.find(x=> x.TEST1 === '46');

Checkout Array.prototype.find() HERE

Leonardo Wildt
  • 2,529
  • 5
  • 27
  • 56
0

$each will work.. Another option is jQuery Ajax Callback for array result

function displayResultForLog(result) {
  if (result.hasOwnProperty("d")) {
    result = result.d
  }

  if (result !== undefined && result != null) {
    if (result.hasOwnProperty('length')) {
      if (result.length >= 1) {
        for (i = 0; i < result.length; i++) {
          var sentDate = result[i];
        }
      } else {
        $(requiredTable).append('Length is 0');
      }
    } else {
      $(requiredTable).append('Length is not available.');
    }

  } else {
    $(requiredTable).append('Result is null.');
  }
}
Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
LCJ
  • 22,196
  • 67
  • 260
  • 418