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?
ajax({ url: 'foo/bar', headers: [{ 'my-first-header': 'blub'}, { 'my-second-header': 'peng'}] }); This creates a strange empty header field, containing a json array.
In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With