1

I'm making an ajax call using jQuery's library to an api, which requires a username and password encoded to base64 be added to the header.

here's a basic example:

$.ajax({
    type: "GET",
    contentType: 'application/json',
        beforeSend:function(xhr){
        xhr.setRequestHeader("Authentication", "Basic " + base64EncodedValue);
    }
    url: 'https://api.company.com/uri/',
    complete: function(result) {
       alert(result);
    }
});

But when this fires off, I get a black alert box, so it doesn't appear as if something is coming back. There is no log in the Firebug console that a get ajax request was done.

However, if I remove the beforeSend option, I do see the ajax request get logged, but the request gets back a 'not authorized', so it definitely hit the right place.

Any ideas on why it's not showing up in Firebug so I can verify the headers are being sent out correctly?

MPelletier
  • 16,256
  • 15
  • 86
  • 137
User
  • 3,662
  • 6
  • 27
  • 23

2 Answers2

1

I would say it's because you don't have a ',' before url...

$.ajax({
    type: "GET",
    contentType: 'application/json',
        beforeSend:function(xhr){
        xhr.setRequestHeader("Authentication", "Basic " + base64EncodedValue);
    }
    ,url: 'https://api.company.com/uri/',
    complete: function(result) {
       alert(result);
    }
});

could be wrong, but that's my guess,

Andrew

Andrew
  • 3,650
  • 9
  • 31
  • 32
0

Having just had a similar problem, it seems like JQuery does not support setting the Authentication header for a cross-domain request.

I had, in a script served from port 80:

    $.ajax({
        beforeSend : function(req) {
            req.setRequestHeader('Authorization', auth);
        },
        url: 'http://localhost:8282/Blahblah',
        success: function(data) {
          console.log("data=" + data);
        }
    });

And I did not see the Autorization-header being set on the request. I changed it to

    $.ajax({
        beforeSend : function(req) {
            req.setRequestHeader('Authorization', auth);
        },
        url: 'http://localhost/Blahblah',
        success: function(data) {
          console.log("data=" + data);
        }
    });

What seems to be happening is that JQuery detects that this is a cross-domain request (in my case because of the difference in port, in your case probably because of a different host?) and silently switches to JSONP which does not support Basic Auth.

See How do I make a JSONP call with JQuery with Basic Authentication?

I realize your question is old, but Google took me here and it could take others here.

Community
  • 1
  • 1
ivarni
  • 17,658
  • 17
  • 76
  • 92