Legend Legend - 3 months ago 15
Javascript Question

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?

if(userVisit != 1) {
// First time visitor
populateData();
}

function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}

function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}

$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}


So what the code does is, it gets a list of predefined identifiers for a new user (
populateData
function) and uses them to get more information from a thirdparty service (
getInformation
function). This
getInformation
function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?

Answer

In your getInformation() call you can call location.reload() in your success callback, like this:

success: function(json) {
  if(!json.error) location.reload(true);
}

To wait until any further ajax calls complete, you can use the ajaxStop event, like this:

success: function(json) {
  if(json.error) return;
  //fire off other ajax calls
  $(document).ajaxStop(function() { location.reload(true); });
}
Comments