I have a number of AJAX requests that are sent from a for loop, and want to send some data to the call back functions depending on the position in the loop.
When I try to attach a function to each request, they all seem to get the data from the last call, for instance,
for(var i=0; i < 4; i++){
data = ... //some unique data
req = $.post('/update/add', data, function(r_data, textStatus, jqxhr){
console.log(data);
}, "json")
}
Would give me the data from the i = 3 entry instead of 4 different entries. How can I pass those data to the callback functions?
Thank you guys...
The problem is that when a closure is created over the
i
variable, it references the same variable instead of creating a newi
variable. To avoid this undesirable effect, you can do the following.In the example above, we are wrapping our callback function in a self-executing function that is being passed the loop's
i
value. Since thei
variable is defined in the scope of the self-executing function, we can now safely return a new callback function that will create a closure over thei
variable of the self-executing function instead of thei
variable used in the loop.NOTE: To optimize your code, you could avoid creating a new self-executing function each time.