How to show loading image in each ajax call using Jquery?


In this article i am going to explain how to show loading image in each AJAX call using Jquery. For each AJAX call in the application three Jquery events will called. Those are ajaxStart(),ajaxStop(),ajaxError()

For each application call Jquery AJAX events will called. Mainly those are
1.ajaxStop()
2.ajaxStart()
3.ajaxError()
First we will write a css class. That class is for a div tag if this class is applied a loader will come. Here we need a Loader image.

CSS Class


.Load
{
background: url("/Images/Loading.png") no-repeat;
height: 75px;
width: 75px;
}

Jquery ajaxStart() code

$(body).ajaxStart(function()
{
$(this).append('<div class=".Load"></div>');
});

when any ajax call is called then this above ajaxStart code will fired and Load class div will be appended to the body tag
Jquery ajaxStop() code

$(body).ajaxStop(function()
{
$(this).remove('.Load');
});

when any ajax call is stopped then this above ajaxStop code will fired and Load class div will be removed from the body tag.

If any error was coming at the server then also ajaxStop event will called but its better handle that kind of situations.
Jquery ajaxError() code


$(body).ajaxError(function()
{
$(this).remove('.Load');
});



we can write ajaxStop and ajaxError in single code that is Like


$(body).ajaxStop(function()
{
$(this).remove('.Load');
}).ajaxError(function()
{
$(this).remove('.Load');
});


Comments

Guest Author: Pesaru19 Sep 2013

Awesome issues here. I'm very satisfied to look your article. Thank you so much and I'm having a look ahead to touch you. Will you please drop me a mail?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: