jQuery AJAX Cross Domain with BASIC Authentication

11,591

Solution 1

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

Solution 2

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.

Share:
11,591
aaronhuisinga
Author by

aaronhuisinga

Just a programmer.

Updated on June 05, 2022

Comments

  • aaronhuisinga
    aaronhuisinga almost 2 years

    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!

  • aaronhuisinga
    aaronhuisinga almost 12 years
    Even with the right password it was giving me the same auth error.
  • muthu
    muthu almost 12 years
    I got error like this GET aaronh.beanstalkapp.com/api/… 401 (Unauthorized)