Add custom http header to all jQuery AJAX Requests

Point of clarification: I don't have any problem adding a custom header to my jQuery ajax call, I want to have my custom header added to all ajax calls automatically.

If you take a look at jquery $.ajax custom http headers issue (not my question), you'll see a pretty good example of how the code works if implemented by hand for each ajax call.

I'd like to override beforeSend for all jQuery ajax calls. According to the jQuery documentation I can do this by using jQuery.ajaxSetup(), but there is a warning saying you probably shouldn't, may cause unexpected behavior, all that stuff. For global callbacks of this kind they suggest using .ajaxStart(). .ajaxStart() looks great, except it doesn't expose the XHR so I can add the header.

Should I just add beforeSend using ajaxSetup? Is there a way to access the XHR from ajaxStart? Other options?

Answers


A pre-filter would be an easy way of accomplishing this:

$.ajaxPrefilter(function( options ) {
    if ( !options.beforeSend) {
        options.beforeSend = function (xhr) { 
            xhr.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE');
        }
    }
});

this way all requests will get the custom header, unless the specific request overrides the beforeSend option.

Note however you can accomplish the same goal using ajaxSetup. the only reason that warning is there is because using it will affect all ajax requests (just like my method will), possibly resulting in unwanted results if a specific request didn't need that option set. I'd suggest just using ajaxSetup, that is what it's there for after all.


You can use the ajax global event ajaxSend()

$( document ).ajaxSend(function( event, jqxhr, settings ) {
    jqxhr.setRequestHeader(name, value)
});

Demo: Fiddle


Need Your Help

Alternative to setAlpha in api level 8

android android-4.2-jelly-bean android-2.2-froyo

I am working on an app, which can run on Froyo as well as JellyBean. I have a class that extends PageTransformer as below:

how to add button click event in android studio

java android button view android-studio

So I have done some research, and after defining you button as an object by the code