Depending on the context of your application, you can subscribe callbacks to fire on certain global AJAX events. Say, whenever an AJAX call starts, or whenever an AJAX call throws an error.
$(document)
.ajaxStart(function (e) {
$('body').showMyAwesomeLoadingGIF();
})
.ajaxComplete(function (e) {
$('body').hideMyAwesomeLoadingGIF();
});
This will cause those two callback functions to fire during the appropriate lifecycle events on every AJAX call made in your document.
If, for some reason, you want a certain AJAX call not to trigger your global AJAX event handlers, you can specify that that particulat AJAX call is not global.
$.ajax({
global : false,
// blah
})
More information on global AJAX event handling here.
EDIT
If you want to maintain a bit more granular control, there's $.ajaxSetup()
, but since jQuery themselves discourages its use, I'm thinking you might be left with having to fashion your own solution.
Personally, I'd use a wrapper function with a closure to set my custom option values if they're something you expect to do repeatedly.
var ajax = (function () {
var defaults = { };
return function (opts) {
opts = $.extend({}, defaults, opts);
// place what you want to happen when an AJAX call starts here
return $.ajax(opts)
// place corresponding events here
.done(function (m) {
})
.fail(function (x,s,e) {
})
.complete(function (m) {
});
};
}());
// then use that in your code like how you'd use $.ajax():
ajax({
url : 'http://my.domain.com/api/users',
type : 'GET'
}).done(function (m) {
console.log('Done GET users.');
});
// ... and you can be sure that it has default options and default event handlers,
// while being able to add on to them if you wish.
$.ajax
. Look for it on the docs, there you get success and error callbacks (and many others).error
callback should do.