I think you are right.
This method is too global...
However - it is a good default for when your AJAX call has no effect on the page itself. (background save for example). ( you can always switch it off for a certain ajax call by passing "global":false - see documentation at jquery
When the AJAX call is meant to refresh part of the page, I like my "loading" images to be specific to the refreshed section. I would like to see which part is refreshed.
Imagine how cool it would be if you could simply write something like :
$("#component_to_refresh").ajax( { ... } );
And this would show a "loading" on this section.
Below is a function I wrote that handles "loading" display as well but it is specific to the area you are refreshing in ajax.
First, let me show you how to use it
<!-- assume you have this HTML and you would like to refresh
it / load the content with ajax -->
<span id="email" name="name" class="ajax-loading">
</span>
<!-- then you have the following javascript -->
$(document).ready(function(){
$("#email").ajax({'url':"/my/url", load:true, global:false});
})
And this is the function - a basic start that you can enhance as you wish. it is very flexible.
jQuery.fn.ajax = function(options)
{
var $this = $(this);
debugger;
function invokeFunc(func, arguments)
{
if ( typeof(func) == "function")
{
func( arguments ) ;
}
}
function _think( obj, think )
{
if ( think )
{
obj.html('<div class="loading" style="background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;"> Loading ... </div>');
}
else
{
obj.find(".loading").hide();
}
}
function makeMeThink( think )
{
if ( $this.is(".ajax-loading") )
{
_think($this,think);
}
else
{
_think($this, think);
}
}
options = $.extend({}, options); // make options not null - ridiculous, but still.
// read more about ajax events
var newoptions = $.extend({
beforeSend: function()
{
invokeFunc(options.beforeSend, null);
makeMeThink(true);
},
complete: function()
{
invokeFunc(options.complete);
makeMeThink(false);
},
success:function(result)
{
invokeFunc(options.success);
if ( options.load )
{
$this.html(result);
}
}
}, options);
$.ajax(newoptions);
};