ajaxSetup (beforeSend not working ajaxSetup (beforeSend not working ajax ajax

ajaxSetup (beforeSend not working


Updated Answer

As of jQuery 1.5 .ajax supports headers property

$.ajax({    url: "http://fiddle.jshell.net/favicon.png",    headers: {        'Authorization': authorization    }}).done(function( data ) {    if ( console && console.log ) {        console.log( "Sample of data:", data.slice( 0, 100 ) );    }});

Notes: the authorization variable should be set somewhere before this call


Old Answer

$(function(){    $.ajaxSetup({        beforeSend: function(xhr) {                 xhr.setRequestHeader('Authorization', authorization);             }    });});

For the ajaxSetup to work you need to call it in the document.ready.


I know this is an old question, but I came here from Google and thought other people searching the same thing should have a working solution. I have tried the suggested answer but it does not work for me.

A solution which solved my problem is to set header directly in xhr object inside of $.ajaxSend:

$(document).ajaxSend(function(ev, xhr, settings) {  xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem(AUTH_TOKEN)}`);  xhr.setRequestHeader('X-Marketplace', localStorage.getItem('marketplace'));});

You should call it in the document.ready for the ajaxSend to work.

That similar question helped me.