Adding basic http authorization in a ajax json script

Not really sure how to add authentication in an ajax call for JSON information. I am trying to follow the examples given http://domainapi.com/documentation/how-to-use-domainapi/servuces-provided/domain-availability-api.html to check the availability of a domain name, however it keeps doing a http form pop up asking for username and password.

I thought I had everything right in my code:

function domainAvailabilityCheck(domain) {
    $.ajax({
        type: 'GET',
        url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
        beforeSend: setHeader,
        success: function(spitback) {
            console.log(spitback.content.domainList.status);
        },
        dataType:'jsonp'
    });
}

var setHeader = function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}

Not sure what it is that I am doing wrong.

Answers


Your beforeSend isn't allowing Jquery to pass in the xhr object for the header modifications. The line should be

beforeSend: function(xhr) { xhr.setRequest(......); } // all-in-one, no extra function needed

or

beforeSend: function(xhr) { setHeader(xhr); } // call your separate function

you may also:

var setHeader = function (xhr) {
    xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}

function domainAvailabilityCheck(domain) {
    $.ajax({
        type: 'GET',
        url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
        beforeSend: setHeader,
        success: function(spitback) {
            console.log(spitback.content.domainList.status);
        },
        dataType:'jsonp'
    });
}

actually it doesn't matter where to put the variable setHeader which holds the anonymous function, but this way up it's more readable (for me and my soft-compiler ... ;)


Need Your Help

JavaScript & jQuery: Change variable and check value

javascript jquery variables

I have problem with JavaScript/jQuery. I'm trying to change variable's value after dialog is displayed and if checbox is checked, but this don't work when I check value of it. What can I do instead...

Compare date from php and MSSQL to retrieve the nearest date from now

php sql-server date datediff

I want to compare MMSQL date together and i want to retrieve the nearest date from now.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.