6

I'm able to recieve the requested xml with

curl -X GET -u username:password url

but not with

$.get('url',
        {username:"username",password:"password"},
        function (data) {


        });

No javascript errors, no cross domain policy issues. It might be a syntax error but I failed to find a decent tutorial yet. Any suggestions please?

Fotis Adamakis
  • 284
  • 1
  • 4
  • 12
  • 1
    possible duplicate of [How to use Basic Auth and Jquery and Ajax](http://stackoverflow.com/questions/5507234/how-to-use-basic-auth-and-jquery-and-ajax) – Manse Apr 19 '12 at 10:42
  • 1
    @fotis can you explain about the curl command ? is it in any browser ? shoudl i download something ? – Royi Namir Apr 19 '12 at 11:04
  • @RoyiNamir It's a [php command](http://php.net/manual/en/book.curl.php) but you can run it on a linux terminal. – Fotis Adamakis Apr 19 '12 at 11:39

3 Answers3

23

I think you'd need the plain format :

$.ajax({
    type: 'GET',
    url: 'url',
    dataType: 'json',
    //whatever you need
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth(user, password));
    },
    success: function () {});
});

function make_base_auth(user, password) {
    var tok = user + ':' + password;
    var hash = btoa(tok);
    return 'Basic ' + hash;
}
Sergio Acosta
  • 11,418
  • 12
  • 62
  • 91
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
3

As an alternative to beforeSendyou could use the headers property to add the authorization header.

$.ajax({
    type: 'GET',
    url: 'url',
    dataType: 'json',
    headers: {
        "Authorization": make_base_auth(user, password)
    }
    success: function () {});
});
Stuart Hallows
  • 8,795
  • 5
  • 45
  • 57
1

As pointed in the other answer, you should be using beforeSend function of Jquery Ajax to add authorization header

function setAuthHeader(xhr){
            var creds = username + ':' + password;
            var basicScheme = btoa(creds);
            var hashStr = "Basic "+basicScheme;
            xhr.setRequestHeader('Authorization', hashStr);
    }

  $.get('url',
         beforeSend: setAuthHeader,
        function (data) {


     });
Satish
  • 6,457
  • 8
  • 43
  • 63
  • 7
    if it was pointed out in the other answer - why not upvote that one instead of adding the same answer ?!?! – Manse Apr 19 '12 at 10:53