I have a foreach loop on some items with an id, in which I have an ajax call. In success function, I want to attribute each response to its corresponding id. How can I do that? Because in succes my id is lost. How can I do something like that:
for (i=0; i<items_to_print.length; i++) {
var item = items_to_print[i];
jQuery.ajax({
url: item.url,
dataType: "json",
data: item.data,
success: function(response, i) {
items_to_print[i]['response'] = response;
}
});
}
Thank you,
2
Answers
One way to do it is to slow the loop down – only go to the next item in the array once you get a response.
Your problem here is that, when the
success
is called,i
points to the last position of the array, so all responses are added to the last item (and only the last one that finishes perdures). This happens because the closure thatsuccess
creates capturesi
, but the variable itself, not its current value when the function is defined, so all closures share the same reference to a variable — a variable that is being modified by the loop. To prevent this, you can useforEach
instead of afor
loop:Doing it this way, for each item in the array you are calling a function, and so the
item
variable is different for each call, sosuccess
can capture it without a problem as it always points to the same object — the one for which the request was made.