Reputation: 1683
I have an ajax request within an ajax request that is inside a loop. Here it is:
for (var i = 0; i < input_files.length; i++) {
$.ajaxFileUpload({
url : dasdasdsa,
success : function () {
$.ajax({
var get_the_number_in_the_last_of_array = input_files[i].split('_').pop();
});
}
});
}
putting async: false
doesnt work. How to go around this? What i want is that every loop the inner ajax gets the right variable i
. What happens in my code is that the inner ajax always gets the last i
.
Note: variable input_files
is an array containing ids, example "my_id_number_9". That 9 in the last is what i want to get in the split.
Upvotes: 2
Views: 775
Reputation: 19
Try closure function
for (var i = 0; i < input_files.length; i++) {
(function(i)
{
$.ajaxFileUpload({
url : dasdasdsa,
success : function () {
$.ajax({
var get_the_number_in_the_last_of_array = input_files[i].split('_').pop();
});
}
});
})(i);
}
Upvotes: 0
Reputation: 388316
The problem is the usage of closure variable i
inside a async callback method.
Since input_files
is an array you can fix it easily using $.each() to iterate
$.each(input_files, function (idx, file) {
$.ajaxFileUpload({
url: dasdasdsa,
success: function () {
$.ajax({
var get_the_number_in_the_last_of_array = file.split('_').pop();
//or var get_the_number_in_the_last_of_array = input_files[idx].split('_').pop();
});
}
});
})
The problem... inside the ajax callback method the variable i
is used which is declared in the outer closure scope so all the ajax request callback methods share the same instance of i
. Now what happens is since the request is asynchronous the loop is finished before the callback is executed so when the callbacks are executed i
will be equal to input_files
which will result in input_files[idx]
giving undefined as the value
The proposed solution will create a private closure for each iteration of the loop which will preserve values of variable declared within the closure from being modified other loops.
Upvotes: 2
Reputation: 29166
Use closure
to pass the correct value of i
-
for (var i = 0; i < input_files.length; i++) {
(function (index) {
$.ajaxFileUpload({
url : dasdasdsa,
success : function () {
$.ajax({
var get_the_number_in_the_last_of_array = input_files[index]
.split('_').pop();
});
}
});
})(i);
}
Upvotes: 4