Rectangle 27 1

How to show loading spinner in jQuery?


$(document).ajaxStart ->
    $(".loading").show()

  $(document).ajaxStop ->
    $(".loading").hide()
$(document).ajaxStart(function() {
  $(".loading").show();
});

$(document).ajaxStop(function() {
  $(".loading").hide();
});
Note
Rectangle 27 1

How to show loading spinner in jQuery?


$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;
var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

If using jQuery >= 1.9, attach the ajaxStart and ajaxStop events to $(document). jquery.com/upgrade-guide/1.9/

That's probably too global for one simple load into a DIV.

The ajaxStart/Stop functions will fire whenever you do any Ajax calls.

There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document. This would transform the above snippet to:

this way unfortunately you can't control loading div positioning in case you don't want to just show a modal loading window, but show it near the element waiting for ajax content to be loaded in...

too global? how many different "please wait" messages do you want?

Note
Rectangle 27 1

How to show loading spinner in jQuery?


<script>
     $(document).ready(function () {
          $(document)
          .ajaxStart(function () {
               $("#ajaxSpinnerImage").show();
          })
          .ajaxStop(function () {
               $("#ajaxSpinnerImage").hide();
          });

          var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
          $.getJSON(owmAPI)
          .done(function (data) {
               alert(data.coord.lon);
          })
          .fail(function () {
               alert('error');
          });
     });
</script>
<style>
     #ajaxSpinnerImage {
          display: none;
     }
</style>

<div id="ajaxSpinnerContainer">
     <img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>

Basically your HTML markup and CSS would look like this:

I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.

It is as simple as that :)

Note
Rectangle 27 1

How to show loading spinner in jQuery?


$("#message").html('<span>Loading...</span>');

$('#message').load('index.php?pg=ajaxFlashcard');

It will be hard to manage UI this way. We may need completely different styles for the "loading" text and final message. We can use the callback method mentioned above for handling this problem

You can also replace the span tag with an image tag.

You can simply assign a loader image to the same tag on which you later will load content using an Ajax call:

Note
Rectangle 27 1

How to show loading spinner in jQuery?


$('#myForm').ajaxSend( function() {
    $(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
    $(this).removeClass('loading');
});
.loading > * { display:none; }
.loading {
    display: block;
    background: url(spinner.gif) no-repeat center middle;
    width: 124px;
    height: 124px;
    margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
    display: none;  
}

As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?

Example CSS, to hide #myForm with a spinner:

Note
Rectangle 27 1

How to show loading spinner in jQuery?


$.ajax({
        url: requestUrl,
        data: data,
        dataType: 'JSON',
        processData: false,
        type: requestMethod,
        async: true,                         <<<<<<------ set async to true
        accepts: 'application/json',
        contentType: 'application/json',
        success: function (restResponse) {
            // something here
        },
        error: function (restResponse) {
            // something here                
        }
    });

Note that you must use asynchronous calls for spinners to work (at least that is what caused mine to not show until after the ajax call and then swiftly went away as the call had finished and removed the spinner).

Note
Rectangle 27 1

How to show loading spinner in jQuery?


If you don't want to write your own code, there are also a lot of plugins that do just that:

Note
Rectangle 27 1

How to show loading spinner in jQuery?


$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');

        $.ajax({
            url:  uri,
            cache: false,
            success: function(){
                $('#loading-image').html('');           
            },

           error:   function(jqXHR, textStatus, errorThrown) {
            var text =  "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
           $('#loading-image').html('<span style="color:red">'+text +'  </span>');

            }
        });

Shortest way would be to insert image tag with an image downloaded from ajaxload.info with transparent background

Note
Rectangle 27 1

How to show loading spinner in jQuery?


$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
  $("#myDiv").html('');
});

Nice! but dear , one thing more that I want to display spinner for 2 seconds even the page has already loaded.

This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE might have difficulties with the animation.

Top tip: Preload the spinner.gif in a div with display set to none. Otherwise you might get a bit of a delayed spinner effect as the spinner still downloads.

You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...

nice tip, much simpler than using somebody else's plugin

Note
Rectangle 27 1

How to show loading spinner in jQuery?


jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});

Does not work for me if the ajax call times out (Firefox 28 for Mac).

Don't know what it's worth, but jQuery mentions in it's documentation that using .ajaxSetup() is not recommended. link

Note here that beforeSend is called before every call, whereas ajaxStart is triggered only when the first ajax method is called. Likewise for ajaxStop, it is called when the last ajax call finishes. If you have more than one concurrent request, the snippet in this answer won't work properly.

This one was cleanest for me. Instead of ajaxSetup, I placed beforeSend: and complete: inside the $ajax({... statement.

works for me, the html should have something like: <div id='loader'><img src="spinner.gif"/></div>

Note