I’m new here.
$.each(a, function (i, obj) {
$('#labelid').html("inserting this data: "+obj.somedata);
// some other code
$.ajax({
// ajax request with insert
});
});
I have an each loop and inside of it is an ajax request that will just insert some data, along with some other code mostly for changing a sort of “status” label (“inserting this: (some data)”).
My problem is when the loop executes, the code inside it except the ajax request iterates all the way to the end, showing in my label something like “inserting this: (last element row)” while the ajax request is still running in the background.
I want to achieve something like this:
1. Label shows “inserting 1st set of data”
2. ajax request inserts 1st set of data
3. Label shows “inserting 2nd set of data”
4. ajax request inserts 2nd set of data
Is this possible? I don’t want to use async: false.
Thanks
4
Answers
Because, Ajax Requests are asynchronous, So Your loop will not wait for its response and immediately move to next one. To perform Ajax as Synchronous You need to add following option.
A for loop will not work in this case because the requests are async. You have 2 options.
of a request arrives. This can be done by creating a recursive function.
Here is little promise wrapper over jQuery Ajax. I think it’ll work with
$.each
.Wrap your ajax request inside a promise and use await to call the promise, hence the execution of code wait for the promise to return response of ajax request and you can set the label in the required format.