The problem is the following, I have an array, I perform a for that traverses this array and for each element inside the array it performs an AJAX request, and even though I put the async: false property, apparently it is still an asynchronous request, which does so that the variable i inside the for loops through everything and only performs the request on the last element of the array.
for(let i = 0; i < array.length; i++){
let elemnt = array[i]
console.log(i)
$.ajax({
async: false,
url: 'https://xxx.xxxxxxxxxx.xxx.xx/'+elemnt,
type: 'GET',
success: (data)=>{
//does something with array element...
}
})
}
putting the console.log(i) was then to output:
0
*Perform AJAX request with array[0]*
1
*Perform AJAX request with array[1]*
2
*Perform AJAX request with array[2]*
however it stays:
0
1
2
*Perform AJAX request with array[2]*
I believe this is all due to Ajax's Asynchronous realization, but I already put async: false, I don't know what else it could be.
Thanks in advance for anyone who can help.
Instead of looping through the array and running ajax in the loop, create a function that ONLY continues when ajax is successful.
In the below example, cur is the position in the array to grab the value from. For the ajax call, I shortened it just for my answer obviously you will need to use your full ajax.
let cur = 0;
function runAjax() {
$.ajax({
......
success: (data) => {
if (cur == array.length) {
console.log("Done!");
} else {
cur++;
runAjax();
}
}
});
}