Our users may get confused if they initiate an Ajax driven process but have no indication that something is happening. They may even think things are broken and abandon or abuse the application trying to fix it (clicking the link again and again.... ).
We can avoid this problem by simply showing a "loading" indicator of some sort. Some applications show the text "Loading...", while others use an animated image. Either way we can provide these visual indicators by hiding or showing content on our page.
To begin, we need the content. A typical approach is to place a DIV where we need it, and in that DIV we include an image.
We have assigned an ID value to our DIV so we can easily refer to it. We have also set our display style to "none" so that the DIV is hidden when the page first loads.
Now, we need to tell that DIV to show itself when an Ajax method is in process, and hide itself when that process is done. We use the .ajaxStart() and .ajaxStop() methods for this.
$("#ajaxindicator").ajaxStart( function() { $(this).show(); } );
$("#ajaxindicator").ajaxStop( function() { $(this).hide(); } );
OR
$("#ajaxindicator").ajaxStart(function() {
$(this).show();
}).ajaxStop( function () {
$(this).hide();
});
The second sample (after the OR) is identical to the first, except we are making use of jQuery's chaining abilities to continue referring to the same element. In both cases we are first getting a reference to our #ajaxindicator DIV (we could have called it #bob instead if we wanted - as long as the DIV's ID attribute was changed accordingly). Now that we have the reference to our DIV we say that when an Ajax method starts, we want to show the DIV ( $(this).show() ). Then we say that when the Ajax method stops we want to hide the DIV ( $(this).hide() ).
Within the .ajaxStart() and .ajaxStop() we can do anything we'd like that would make sense. Perhaps we need to remove some page elements, or want to set the background color or styles for the elements being affected. This is the place to do it.
There are other Ajax events we can respond to in a similar manner - there is the .ajaxSuccess(), .ajaxError(), and .ajaxSend() events. Making use of these other events would follow a similar pattern as our sample code above. All the details can be found on the official jQuery Ajax documentation.