ajaxSetup (beforeSend not working

25,685

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.

Share:
25,685
Admin
Author by

Admin

Updated on December 07, 2020

Comments

  • Admin
    Admin over 3 years

    after login to remote aPI server, and getting an access_token, I try to set the authorization header for all subsequent ajax calls :

          .done(function (result) {
             console.log("GOT AUTHORIZATION");
             amplify.store( "tokens", { access_token: result.access_token, refresh_token: result.refresh_token, token_type: result.token_type, expires_in: result.expires_in });
             var authorization = 'Bearer ' + amplify.store( "tokens" ).access_token;
             console.log(authorization);
    
             $.ajaxSetup({
                 beforeSend: function(xhr) {
                     xhr.setRequestHeader('Authorization', authorization);
                 }
             });
    

    on console I can see :

    GOT AUTHORIZATION login.js:34
    Bearer 6b7578772fbb4178793100651f2234de840237fe
    

    but none of subsequent ajax calls get the correct header set :

    https://macmini.local:8000/Categories?_=1381758170726 
    

    cannot succeed as no access_token is found in the header ( server console ..)

    { code: 400,
       error: 'invalid_request',
       error_description: 'The access token was not found',stack: undefined }
    saveAccessToken: 6b7578772fbb4178793100651f2234de840237fe, client_id: 1234567890, user_id: 1
    

    I tried to modify the header inside the ajax call wo any success

  • Admin
    Admin over 10 years
    Thanks ... it's working this way... I found also how to make the beforeSend working inside the ajax call block... I forgot to add : async:false .. $.ajax( 'macMini.local:8000/Categories', { type: "GET", cache: false, async: false, dataType: "json", beforeSend: function (xhr, settings){ xhr.setRequestHeader('Authorization', 'Bearer ' + amplify.store( "tokens" ).access_token); } })
  • MonoThreaded
    MonoThreaded about 8 years
    this is probably outdated now you can just set "headers" property directly in $.ajax()
  • abc123
    abc123 about 8 years
    @MonoThreaded updated answer, thanks for point this out to me. Without you I wouldn't notice this.