var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
var xhr = _orgAjax();
DoSomeLogging();
return xhr;
};
I’ve inherited the code above. Can someone confirm my understanding that this will override any $.ajax(...) call anywhere else on the page and execute DoSomeLogging() each time?
I’m hunting a different bug but stumbled upon this and wanted to be sure I understand what this piece of legacy code does?
I’m not convinced this is good practice/use of the xhr function anyway but interested to hear your opinions. We’re using Jquery 1.7.1.
Lastly, out of curiosity, what if _orgAjax() failed to return if an (async: false) call, would the logging method even get reached?
Thanks.
Yes. This will define the global default behaviour unless overwritten in a local ajax implementation.
The more documented way of defining global settings is the use of ajaxSetup().
However, you are able to set default global behaviour using
ajaxSettingsas well, though this particular way is not documented anywhere directly in the jQuery documentation.See DEMO – With Success
The settings are configuring the
beforeSendso the logging method will always be called regardless of the async setting as pointed out correctly by Esailija.See DEMO – with
async: true, logging is called before returnSee DEMO – with
async: false, logging is also called before returnHowever please note though, according to the ajax documentation:
I know you are using 1.7.1 but if something becomes deprecated there usually is a good reason and I don’t see any harm in preparing for that.
To configure ajax with logging on
completeby default:See DEMO – Configuring default logging for
completefor document.I know that would make your logging being executed after and not before the send but that seems to be the way 1.8 prefers it I think.