I have a bunch of jQuery AJAX post requests wrapped up in a for loop. Each request provides a different parameter. My question is, in the event of the request failing, how can you tell what parameter data was passed by that request?
When I try:
for(i = 0; i < toSubmit.length; i++) {
$.post('doSomething.php',
{id: toSubmit[i]},
function(data) { /* Do something here */ },
'json')
.error(function() {
console.log(toSubmit[i] + " didn't work!");
});
}
…the error function will just output the last value in toSubmit, because the i pointer has progressed all the way through the for loop, while the requests are fired asynchronously. The same thing occurs in the success and complete function; the way I’ve got around that is to make sure the returned JSON contains the respective id; but if the request fails, I can’t use this workaround.
Is there a way for me to get at this information, or is there a better way of firing off these requests?
It seems you have to set the correct context for the method call. You can look into the jQuery proxy() method which allows you to provide the correct context for the callback.
Try something like this: