Fotis Adamakis Fotis Adamakis - 2 months ago 8
jQuery Question

Ajax authentication with jQuery

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?

Answer

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;
}
Comments