Customizing $.getJSON for a specific loading panel

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($) {
        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() {
                complete: function() {
                success: callback,
                data: data

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) {

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.