jQuery loop over JSON result from AJAX Success?

JqueryAjaxJson

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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.

Solution 3 - Jquery

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

Solution 4 - Jquery

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");
	}
});

Solution 5 - Jquery

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

Solution 6 - Jquery

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);

Solution 7 - Jquery

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>

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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

Solution 11 - Jquery

$each will work.. Another option is https://stackoverflow.com/questions/13683263/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.');
  }
}

Solution 12 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaherrickView Question on Stackoverflow
Solution 1 - JquerycletusView Answer on Stackoverflow
Solution 2 - Jqueryclone45View Answer on Stackoverflow
Solution 3 - Jquery0100110010101View Answer on Stackoverflow
Solution 4 - JqueryDave HilditchView Answer on Stackoverflow
Solution 5 - JqueryJon RView Answer on Stackoverflow
Solution 6 - JqueryYovavView Answer on Stackoverflow
Solution 7 - JqueryPanwarS87View Answer on Stackoverflow
Solution 8 - JqueryThe Billionaire GuyView Answer on Stackoverflow
Solution 9 - JquerydimitarView Answer on Stackoverflow
Solution 10 - JqueryFrederick EzeView Answer on Stackoverflow
Solution 11 - JqueryLCJView Answer on Stackoverflow
Solution 12 - JqueryLeonardo WildtView Answer on Stackoverflow