Can I set a global header for all AJAX requests?

This doesn't seem to be working :

  headers: {
    Accept: 'application/;version=1 ',
    Authorization: 'Token token=\"FuHCLyY46\"'

I would have thought it would. If I add these filters specifically to my AJAX call then they do work. I'd like to do this globally for all AJAX calls.



I did some additional tests and the code you posted works perfectly. If you have problems with something in how the parameters are setup, you could always to go the beforeSend call and modify the xml request yourself.

    beforeSend: function (xhr)
       xhr.setRequestHeader("Authorization","Token token=\"FuHCLyY46\"");        

It's also possible to do this in a framework-agnostic way by monkey-patching the open method:

var o =; = function(){
  var res = o.apply(this, arguments);
  var err = new Error();
  this.setRequestHeader('X-Ajax-Stack', JSON.stringify(err.stack));
  return res;

In this example I'm sending stack trace information via a header, which allows the backend to know where Ajax requests originated, even if it's from third-party code that doesn't use jQuery.

(Note: careful about headers getting too big)


The beforeSend answer does not establish the same header's as adding header directly to the ajax call. So in order for jQuery to do this properly I add this :

headers: myGlobalHeaders

where myGlobalHeaders is a global variable. Unfortunately, I have to write this extra line on every single ajax call. Terrible! Maybe I'll edit the jQuery framework to handle this..


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.