Reputation: 5414
I have a loop that sends multiple ajax request.
When all these are completed I want to reload my page.
$.each(uuids, function (i, e) {
console.log("Sending request for: " + e)
$.ajax({
type: 'GET',
data: {
_rnd: new Date().getTime()
},
url: addToGroupUrl + '?label=' + encodeURIComponent($("#changeGroupSelect").val()) + '&labelDisplay=' + encodeURIComponent($("#changeGroupSelect option:selected").text()) + '&uuid=' + e,
dataType: 'json',
async: 'false',
});
});
location.reload()
Now I have issues where not all requests are made. The loop creates all requests, but as soon as location.reload() is done the server stop receiving requests.
It seems like async: 'false'
only prepare requests, but that they are handled async.
How am I suppose to think here? I want to reload my page when all requests has been sent.
Upvotes: 0
Views: 46
Reputation: 337560
Firstly the async
property accepts a boolean value, not a string, so it should be async: false
.
Secondly, and far more importantly, NEVER EVER use async: false
. It is horrendous for the user experience because it completely blocks the UI from being updated and makes the browser look like it crashed.
Instead, make all requests asynchronously and place all their promises in an array which you can apply
to $.when
before executing your required code when they all complete. Try this:
var requests = [];
var label = $("#changeGroupSelect").val();
var labelDisplay = $("#changeGroupSelect option:selected").text();
$.each(uuids, function (i, e) {
requests.push($.ajax({
type: 'GET',
data: {
_rnd: new Date().getTime(),
label: label,
labelDisplay: labelDisplay,
uuid: e
},
url: addToGroupUrl,
dataType: 'json'
}));
});
$.when.apply(this, requests).done(function() {
window.location.reload()
});
Note that if you provide the URL parameters to the data
property they will automatically be encoded for you. Also, because the values of the inputs do not change between requests, you can grab them outside of the loop to stop the DOM being needlessly queried in each iteration.
Upvotes: 5
Reputation: 3867
async parameter of ajax, excepts a boolean value, try it like this:
async: false
http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings
Upvotes: 1