I need to count the number of ajaxes. Each ajax is run inside for (however, I cannot use the index of the loop function). Here is my code:
var i = count = 0, formData, blob;
for (/*setting the for loop*/) {
$.ajax({
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(evt){
// here I need to count be 0,1,2,3,4... for every ajax
console.log('Part'+count+'is being uploaded');
};
return xhr ;
},
url: 'upload.php',
type: 'POST',
data: formData,
},
});
count++;
}
Now what I need is to get the info which part is being uploaded. The way it works now is that the count is always the number of the last ajax (for obvious reason: the count is increased and the progress event has not been even fired up yet).
So Is there way to increase the count anywhere else to achieve this? Again, I cannot use the index of the for loop.
NOTE: The code is simplified, the actual code is more complex.
You can do this with a closure, saving the current value of count:
for (/*setting the for loop*/) {
$.ajax({
xhr: ( // Executing a function with count as currentCount,
// then it save the value of count in the returned function (Closure)
function(currentCount){
return function(){
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(evt){
console.log('Part'+currentCount+'is being uploaded'); // here I need to count be 0,1,2,3,4... for every ajax
};
return xhr;
};
})(count)
,
url: 'upload.php',
type: 'POST',
data: formData,
},
});
count++;
}