Reputation: 1032
I'm having a problem with ajax call when deleting an object from an array and updating the list view.
Inside a loop, If I can confirm the deletion of the object online I want to delete that same object from the native array. The problem is that the deletion from the native array does not work and I dunno why.
The code:
for (var i = 0; i < tempShoppingCartArray.length; i++) {
var row = tempShoppingCartArray[i];
if(chosenSubMenuID.sid == row.sid && row.sent == 0){
var myUrl = someURL
$.ajax({
type: "POST",
url: myUrl,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", wsTOKEN);
},
success: function(response) {
tempShoppingCartArray.slice(i,1); //this code does not work
$("#shopping-list li").eq(i).remove(); //this code does not work
},
error: function(jqXHR, exception) {
}
});
}
}
Upvotes: 0
Views: 906
Reputation: 136114
The problem you're having is because although you think that in the success
method of your ajax request that i
will be equal to the current iteration from the for
loop, it will in fact have the final value for all requests.
Take this example:
var array = ["a","b","c"];
for(var i=0;i<array.length;i++){
$.ajax({
method:'GET',
url: '/echo/json',
success: function(){
console.log(i,"success");
}
});
};
You may expect that the output in the console would be
0 success
1 success
2 success
When in actual fact it is
3 success
3 success
3 success
This is due to the asynchronous nature of the ajax call, having made the call control returns immediately and therefore executes all of the 3 requests straight after one another. When the first success
is called, the loop control variable has already reached its limit (3 in this case).
The way to fix this is to produce a scope around the ajax call using an IIFE, and pass the loop control variable in as a parameter, this gives the expected result:
var array = ["a","b","c"];
for(var i=0;i<array.length;i++){
(function(x){
$.ajax({
method:'GET',
url: '/echo/json',
success: function(){
console.log(x,"success");
}
});
})(i)
};
0 success
1 success
2 success
Upvotes: 2
Reputation: 338
I think you want to use the splice function, not slice:
tempShoppingCartArray.splice(i,1);
The slice function is not actually altering the tempShoppingCartArray variable, but rather, calling array.slice(a,b) returns a new array containing the elements in array from index a to index b. With array.splice(a,b), array has b elements after and including the element at index a removed from it.
Also as @Jamiec pointed out, since ajax does asynchronous calls, your i will continue incrementing whilst the request is processing. By the time this finishes i will have reached the length of the array. Try throw a break in after your ajax call.
$ajax(....);
break;
I think that should work.
Upvotes: 1