20

I want a basic spinner or processing animation while my AJAX POST is processing. I'm using JQuery and Python. I looked at the documentation but can't figure out exactly where to put the ajaxStart and ajaxStop functions.

Here is my js:

    <script type="text/javascript">
      $(function() {  
        $('.error').hide();  
        $("#checkin-button").click(function() { 
          var mid = $("input#mid").val();
          var message = $("textarea#message").val();
          var facebook = $('input#facebook').is(':checked');
          var name = $("input#name").val();
          var bgg_id = $("input#bgg-id").val();
          var thumbnail = $("input#thumbnail").val();
          var dataString = 'mid='+mid+'&message='+message+'&facebook='+facebook+'&name='+name+'&bgg_id='+bgg_id+'&thumbnail='+thumbnail;  
          $.ajax({  
            type: "POST",  
            url: "/game-checkin",  
            data: dataString,  
            success: function(badges) {  
            $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");  
            $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");  
            $.each(badges, function(i,badge) {
              $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='"+badge.image_url+"'><span class='badge-title'>"+badge.name+"</span></p>");  
            });
          }
       });
       return false;
     });  
    });
  </script>
Will Curran
  • 6,959
  • 15
  • 59
  • 92
  • A lot of great answers to choose from. I've already tried most of what has been answered and all seem to work well. Many ways to skin this cat. Thanks!! – Will Curran Feb 04 '11 at 18:56
  • 5
    don't skin cats it is cruel and they don't like it – bharal Jun 18 '12 at 02:38

7 Answers7

30
$.ajax({
  type: "POST",
  url: "/game-checkin",
  data: dataString,
  beforeSend: function () {
    // ... your initialization code here (so show loader) ...
  },
  complete: function () {
    // ... your finalization code here (hide loader) ...
  },
  success: function (badges) {
    $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
    $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
    $.each(badges, function (i, badge) {
      $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
    })
  }
});

http://api.jquery.com/jQuery.ajax/:

Here are the callback hooks provided by $.ajax():

beforeSend callback is invoked; it receives the jqXHR object and the settings map as parameters. error callbacks are invoked, in the order they are registered, if the request fails. They receive the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport". dataFilter callback is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success. success callbacks are then invoked, in the order they are registered, if the request succeeds. They receive the returned data, a string containing the success code, and the jqXHR object. complete callbacks fire, in the order they are registered, when the request finishes, whether in failure or success. They receive the jqXHR object, as well as a string containing the success or error code.

Note the beforeSend and complete method additions to the code.

Hope that helps.

daaawx
  • 3,273
  • 2
  • 17
  • 16
Mandrake
  • 1,161
  • 1
  • 10
  • 11
  • 2
    `beforeSend` is a weird place to put spinner code. That's for modifying the XHR object, not manipulating the DOM. You can simply add the spinner before calling `$.ajax`. Nowadays you probably want to stop the spinner using the `.always` promise method. – mpen Jul 02 '15 at 22:33
7

If you're using jQuery 1.5 you could do that nicely, unobtrusively and generically with a prefilter. Let's make a very simple plugin for this:

(function($) {

    var animations = {};

    $.ajaxPrefilter(function( options, _, jqXHR ) {
        var animation = options.animation && animations[ options.animation ];
        if ( animation ) {
            animation.start();
            jqXHR.then( animation.stop, animation.stop );
        }
    });

    $.ajaxAnimation = function( name, object ) {
        if ( object ) {
            animations[ name ] = object;
        }
        return animations[ name ];
    };

})( jQuery );

You install an animation as follows:

jQuery.ajaxAnimation( "spinner" , {
    start: function() {
        // code that starts the animation
    }
    stop: function() {
        // code that stops the animation
    }
} );

then, you specify the animation in your ajax options:

jQuery.ajax({
    type: "POST",
    url: "/game-checkin",
    data: dataString,
    animation: "spinner",
    success: function() {
        // your success code here
    }
});

and the prefilter will ensure the "spinner" animation is started and stopped when needed.

Of course, that way, you can have alternative animations installed and select the one you need per request. You can even set a default animation for all requests using ajaxSetup:

jQuery.ajaxSetup({
    animation: "spinner"
});
Julian Aubourg
  • 11,346
  • 1
  • 29
  • 29
3

you can set global ajax loading icon handler using here #ajxLoader takes your loading icon

   $( document ).ajaxStart(function() {
        $("#ajxLoader").fadeIn();
    });

    $( document ).ajaxComplete(function() {
        $("#ajxLoader").fadeOut();
    });
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    This approach seemed the simplest to implement for my purposes, but doesn't handle multiple ajax calls (it fades out when the first one completes). To solve this I used `ajaxStop` instead of `ajaxComplete`. See the [docs](http://api.jquery.com/ajaxStop/) if you want to use this method. – danj1974 Nov 27 '15 at 09:14
3

The best method I have found, assuming you are populating a present but empty field is to have a .loading class defined with background-image: url('images/loading.gif') in your CSS. You can then add and remove the loading class as necessary with jQuery.

Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
2

The AJAX process starts when you run the $.ajax() method, and it stops when the 'complete' callback is run. So, start your processing imagery/notification right before the $.ajax() line, and end it in the 'complete' callback.

ajaxStart and ajaxStop handlers can be added to any elements, and will be called whenever ajax requests start or stop (if there are concurrent instances, start only gets called on the first one, stop on the last to go). So, it's just a different way of doing global notification if you had, for example, a status spinner somewhere on the page that represents any and all activity.

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
Craig
  • 358
  • 1
  • 9
2
$(function() {
        $('.error').hide();
        $("#checkin-button").click(function() {
                var mid = $("input#mid").val();
                var message = $("textarea#message").val();
                var facebook = $('input#facebook').is(':checked');
                var name = $("input#name").val();
                var bgg_id = $("input#bgg-id").val();
                var thumbnail = $("input#thumbnail").val();
                var dataString = 'mid=' + mid + '&message=' + message + '&facebook=' + facebook + '&name=' + name + '&bgg_id=' + bgg_id + '&thumbnail=' + thumbnail;
                $.ajax({
                        type : "POST",
                        url : "/game-checkin",
                        data : dataString,
                        beforeSend : function() {
                         $('#preloader').addClass('active');
                        },
                        success : function(badges) {
                            $('#preloader').removeClass('active');
                            $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
                            $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
                            $.each(badges, function(i, badge) {
                                    $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
                                });
                        },
                        complete : function() {
                            $('#preloader').removeClass('active');                      
                        }
                    });
                return false;
            });
    });

#preloader{
 background: url(staticpreloader.gif);
}
.active {
 background: url(activepreloader.gif);
}
Idered
  • 2,065
  • 1
  • 18
  • 20
2

I wrote a blog post about how to do this on a generic document level.

// prepare the form when the DOM is ready 
$(document).ready(function() { 

  // Setup the ajax indicator
  $('body').append('<div id="ajaxBusy"><p><img src="images/loading.gif"></p></div>');

  $('#ajaxBusy').css({
    display:"none",
    margin:"0px",
    paddingLeft:"0px",
    paddingRight:"0px",
    paddingTop:"0px",
    paddingBottom:"0px",
    position:"absolute",
    right:"3px",
    top:"3px",
     width:"auto"
  });
});

// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){ 
  $('#ajaxBusy').show(); 
}).ajaxStop(function(){ 
  $('#ajaxBusy').hide();
});
SKFox
  • 1,377
  • 10
  • 16