Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 833
Peter Avatar asked Dec 03 '13 16:12

Peter


People also ask

How can I pass multiple headers in ajax call?

ajax({ url: 'foo/bar', headers: [{ 'my-first-header': 'blub'}, { 'my-second-header': 'peng'}] }); This creates a strange empty header field, containing a json array.

Can I add custom header to HTTP request?

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.

What are headers in ajax call?

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.


2 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.

like image 80
Kevin B Avatar answered Sep 23 '22 00:09

Kevin B


You can use the ajax global event ajaxSend()

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

Demo: Fiddle

like image 32
Arun P Johny Avatar answered Sep 24 '22 00:09

Arun P Johny