erwin erwin - 2 years ago 418
Javascript Question

ajaxSetup (beforeSend not working

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"); "tokens", { access_token: result.access_token, refresh_token: result.refresh_token, token_type: result.token_type, expires_in: result.expires_in });
var authorization = 'Bearer ' + "tokens" ).access_token;

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

on console I can see :

Bearer 6b7578772fbb4178793100651f2234de840237fe

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


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

Answer Source

Updated Answer

As of jQuery 1.5 .ajax supports headers property

    url: "",
    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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download