Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a global header for all AJAX requests?

This doesn't seem to be working :

$.ajaxSetup({   headers: {     Accept: 'application/vvv.website+json;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.

like image 312
Trip Avatar asked Jan 25 '13 17:01

Trip


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.

Which global event is triggered if an AJAX request?

The ajaxStart and ajaxStop events are events that relate to all Ajax requests together. This event is triggered if an Ajax request is started and no other Ajax requests are currently running.

What is global AJAX?

These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery. ajaxSetup() is true , which it is by default.


2 Answers

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.

$.ajaxSetup({     beforeSend: function (xhr)     {        xhr.setRequestHeader("Accept","application/vvv.website+json;version=1");        xhr.setRequestHeader("Authorization","Token token=\"FuHCLyY46\"");             } }); 
like image 146
John Koerner Avatar answered Oct 09 '22 16:10

John Koerner


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

var o = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = 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)

like image 28
Daniel Avatar answered Oct 09 '22 16:10

Daniel