20

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?

2

2 Answers 2

31

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.

1
  • 6
    You don't need to modify the beforeSend function. The jqXHR object is exposed as part of the arguments in the $.ajaxPrefilter(options, originalOptions, jqXHR) function. So you can just write inside the prefilter function jqXHR.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE'); Feb 25, 2016 at 14:15
17

You can use the ajax global event ajaxSend()

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

Demo: Fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.