Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

16.3. Using Simple Ajax with User Feedback

Problem

You need to show a status indicator to the user when Ajax requests are in progress and hide it upon completion.

Solution

(function($) {
    $(document).ready(function() {
        $('#ajaxStatus')
            .ajaxStart(function() {
                $(this).show();
            })
            .ajaxStop(function() {
                $(this).hide();
            });

        // Start our ajax request when doAjaxButton is clicked
        $('#doAjaxButton').click(function() {
            $.ajax({
                url: 'ajax-gateway.php',
                   data: { val: "Hello world" },
                   dataType: 'json',
                success: function(json) {
                    // Data processing code
                    $('body').append( 'Response Value: ' + json.val );
                }
            });
        });
    });
})(jQuery);

Discussion

One of the huge benefits of jQuery’s Ajax implementation is the exposure of global Ajax events that are triggered on all elements with each Ajax request. In the following solution, we bind two of the events, ajaxStart and ajaxStop using the shortcut methods to the XHTML element with the ID ajaxStatus. When the Ajax request is triggered upon clicking #doAjaxButton, the ajaxStart event is also dispatched and calls show() on the #ajaxStatus element. Notice that these events are triggered automatically and are a by-product of using the $.ajax() (or other shortcut methods such as $.get()). This provides an elegant decoupled solution for having an application-wide request status as Ajax requests are submitted:

(function($) { $(document).ready(function() { $('#ajaxStatus') .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); // Start our ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required