I need to count how many times a jQuery ajax call is successfully executed on each item in a list.
I started here, but then realized this won’t work because of the “asynchronous” part of ajax:
var numSuccessfullUpdates = 0;
$('#saveMyListItems').click(function (event) {
event.preventDefault();
$('ul#myList li').each(function () {
$.ajax({
url: '[my_url]',
type: "POST",
data: {
// [data block here, not relevant to question]
},
success: function () {
numSuccessfullUpdates++;
}
});
});
if (successfullUpdates > 0){
alert(numSuccessfullUpdates);
}
});
Any suggestions?
You could use the
completehandler for AJAX and count the status results until the total of results equals to the total of requests. Here is example code, also available as a jsFiddle