I need to pass outside variable to jQuery Ajax's success-function. My ajax is in a loop like so:
var props = ['a', 'b', 'c'];
var results =
{
a: null,
b: null,
c: null
};
for(var key in props)
{
var prop = props[key];
$.ajax(
{
url: 'someurl',
data:
{
somedata: 'somevalue'
},
success: function(data, status, xhr)
{
// This here does not work properly, because the prop's value changes
// Due to promise stuff
results[prop] = data;
}
});
}
I need to stuff the data returned in success in to the correct place, but the implementation above does not work because the value of prop
changes before the success is called.
I found out that I can "bypass" this problem by binding the success-function's this with the prop like so:
success: function(data, status, xhr)
{
results[this] = data;
}.bind(prop)
But this does not seem like a very good idea and besides, I can only bind one variable, not multiple if need be.
This does not seem to work either:
success: function(data, status, xhr)
{
var privprop = prop;
results[privprop] = data;
}
So basically what is the best way to give each success callback a "private" variable, which value is what the value of prop was when the whole ajax was made? Can I somehow bind multiple variables and overwrite something else than this
?