After many years, I’m finally trying to learn Javascript instead of avoiding it. Something that seems basic that I’m having a hard time getting a good tutorial for is a simple loading screen. When my home page is loaded, I need to make 4 ajax calls to get JSON data and store them in localStorage. I simply want to display a loading screen while these calls are being made, and when they are finished, show the UI. How could I do this and insure that all 4 were loaded?
Hi,
Not sure what you mean by loading screen.
Here is a comprehensive tutorial about how to make a div fade in while the AJAX calls are taking place and fade out when they are finished:
http://andrewchaa.me.uk/2012/04/26/show-ajax-loader-image-while-making-ajax-request-with-jquery/
Sorry, yes, you deciphered my bad communication skills correctly. Thank you for the tutorial. I guess to be more specific here, with my case where I have 4 different ajax calls being made, how could I hide the loading div only after all 4 are done? My only idea would be to show the loading message then call the hide function in the success callbacks of each one?
Hi there,
jQuery now defines a ‘when’ function for this purpose.
It accepts any number of deferred objects as arguments, and executes a function when all of them resolve.
So in your case, you could do something like this:
$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
});
function ajax1() {
// NOTE: This function must return the value
// from calling the $.ajax() method.
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
...
});
}
I wish I could take credit for the code, but I can’t.
I found it here: http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-request-are-done
Excellent, exactly what I was looking for, thanks.