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?

asked Dec 3, 2013 at 16:22
2
  • You could add a prefilter, api.jquery.com/jQuery.ajaxPrefilter Commented Dec 3, 2013 at 16:37
  • @KevinB - Can you post that as an answer? Commented Dec 3, 2013 at 17:08

2 Answers 2

32

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.

answered Dec 3, 2013 at 18:09
Sign up to request clarification or add additional context in comments.

1 Comment

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');
17

You can use the ajax global event ajaxSend()

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

Demo: Fiddle

answered Dec 3, 2013 at 16:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.