aaronhuisinga
aaronhuisinga

Reputation: 299

jQuery AJAX Cross Domain with BASIC Authentication

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.

What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.

<script type="text/javascript">
$(document).ready(function() {
    var tok = 'username' + ':' + 'password123';
        hash = btoa(tok);
        authInfo = "Basic " + hash;
    $.ajax({
        url: "http://username.beanstalkapp.com/api/changesets.json",
        beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
        type: "GET",
        async: false,
        crossDomain: true,
        dataType: "json",
        success:  function(html){
            console.log(html);
        },
        error: function(html){
            console.log('error');
        }
    });
});
</script>

If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!

Upvotes: 3

Views: 11850

Answers (3)

svlada
svlada

Reputation: 3288

You will need to make proxy for cross-domain ajax requests.

Usual scenario looks like this:

  1. Client send ajax request to server
  2. Your server forwards request to external/remote server
  3. Waiting on response from remote server
  4. Parse and process response from remote server
  5. Send response back to client

If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.

Upvotes: 4

muthu
muthu

Reputation: 5461

Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

Upvotes: 0

zizoujab
zizoujab

Reputation: 7800

you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.

Upvotes: 1

Related Questions