163

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
});
1
  • 1
    This should work. Are you sure that's exactly the same code and the same data? Commented Apr 9, 2009 at 8:43

12 Answers 12

277

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.

6
  • The first loop is for a "category" while a loop within that is for an "attribute." How else is that done?
    – dcolumbus
    Commented Oct 22, 2010 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
    Commented Nov 4, 2010 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. Commented Oct 17, 2012 at 18:16
  • 2
    Could someone explain the variables k & v that are passed to the second function? Commented Mar 6, 2015 at 19:08
  • 1
    I get this error: Uncaught TypeError: Cannot use 'in' operator to search for '188' in
    – Si8
    Commented Mar 17, 2017 at 16:20
85

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.

1
  • 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
    Commented Jul 3, 2014 at 4: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

0
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");
    }
});
3
  • This is giving me "data is undefined". Commented Nov 2, 2016 at 18:36
  • You should use your own variable that stores the data you are passing to the url. If your data variable is called mydata then use data: mydata Commented Nov 10, 2016 at 18:17
  • Uncaught TypeError: Cannot use 'in' operator to search for '188' in getting that error.
    – Si8
    Commented Mar 17, 2017 at 16:21
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);
}
3
  • 1
    old question, but how could you loop through json keys without knowing the names... like Test1, Test2, ext... Commented Oct 14, 2013 at 22:15
  • @BarclayVision You just use the key as a number. The first key is [0], the next [1], and so on. Commented Jan 21, 2014 at 1:16
  • 1
    can we use another ajax call inside this for loop? If yes then Please tell me How? Commented Aug 2, 2018 at 11:18
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);

0
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>

0
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

2

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]);
      })
})
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>`)
  })
},
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

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.');
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.