Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 294
aaronhuisinga Avatar asked Dec 06 '25 10:12

aaronhuisinga


2 Answers

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/.

like image 149
svlada Avatar answered Dec 07 '25 23:12

svlada


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.

like image 44
zizoujab Avatar answered Dec 07 '25 23:12

zizoujab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!