Journal of a software dev

November 2, 2011

Customizing $.getJSON for a specific loading panel

Filed under: javascript, jQuery — Tags: , , , , , , — Michael Cromwell @ 9:11 pm

If you want to display a loading image for each ajax call made with jQuery you can hook into the global ajax events however you may have screens that have separate areas where the content is loaded async at the same time in which case you want a separate loading image assigned to each, normally you would then need to use either the low level $.ajax function or use the callback functions on the returned jqXHR object, so I have created the following jQuery plugin to allow a selector to be passed that will be shown at load and hidden when completed:

(function($) {
    $.extend({
        getJSON: function(url, loadingSelector, data, callback) {
            if ($.isFunction(data)) {
                callback = data;
                data = null;
            }

            var loadingElement = $(loadingSelector);
            return $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                beforeSend: function() {
                    loadingElement.show();
                },
                complete: function() {
                    loadingElement.hide();
                },
                success: callback,
                data: data
            })
        }
    })
})(jQuery);

The arguments are the same as the standard function apart from the new loadingSelector argument where you specify the element(s) that should be shown on load and hidden when complete here is an example usage:

$.getJSON('/customer/list', '#loading', function(response) {
    $('#customers').html(response.content);
});

This will use the selector ‘#loading’ to select the element(s) you can use any jQuery selector, with some tweaks you could also extend $.post.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.