0

I am trying to access resourced from multiple servers using AJAX, and I am running into this problem:

XMLHttpRequest cannot load http://first.mydomain.com. Origin http://second.mydomain.com is not allowed by Access-Control-Allow-Origin.

With the following code

    for ( i in domains )
    {
        var url = 'http://'+domains[i]+'/mgmt/json/queue_status.php';
        requests[i]=new request(url);
        break;
    }

    function request(url)
    {
        var queues = {};
        http_request = new XMLHttpRequest();
        http_request.open("GET", url, true, 'username', 'password');
        http_request.onreadystatechange = function () {
            var done = 4, ok = 200;
            if (http_request.readyState == done && http_request.status == ok) {
                queues = JSON.parse(http_request.responseText);
                var queuesDiv = document.getElementById('queues');
                print_queues(queues, queuesDiv);                
            }
        }
        http_request.send(null);
    }

I have added the following to response page being requested.

header('Access-Control-Allow-Origin: *');

I have tried explicitly naming the requester too with no success.

Thanks

PS: The above code I am sure ins't perfect but function fine when only trying to requests the resource of the host server.

hakre
  • 193,403
  • 52
  • 435
  • 836
111111
  • 15,686
  • 6
  • 47
  • 62
  • 5
    Classic. This is happening because of the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) – Jacob Relkin Sep 27 '11 at 14:12
  • Ok, but is there any way around this? – 111111 Sep 27 '11 at 14:18
  • Yes, via JSONP callbacks and ` – Jacob Relkin Sep 27 '11 at 14:19
  • http://stackoverflow.com/questions/1300130/explanation-and-usage-of-jsonp – Alex Turpin Sep 27 '11 at 14:21
  • OK, so far as I can tell, JSONP allows you to avoid making the XHR by making the browser get JSON from the remote resource onload, but how can I get it to run this at an interval without just crudely reloading the page. – 111111 Sep 27 '11 at 14:31
  • possible duplicate of [jquery / ajax / soap - access-control-allow-origin](http://stackoverflow.com/questions/7288993/jquery-ajax-soap-access-control-allow-origin) – hakre Sep 27 '11 at 14:32
  • hakre: this is probably what I am going to have to do, it is a PITA though. – 111111 Sep 27 '11 at 14:41
  • Are you sure the http header is actually send? Also what happens if you temporarily remove the username and password arguments? The code looks like it should just work. – Gerben Sep 27 '11 at 16:04

1 Answers1

0

username and password are not allowed in cross origin requests.

Throws an INVALID_ACCESS_ERR exception if either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.

source: http://www.w3.org/TR/XMLHttpRequest2/#the-open-method

Just pass the password and username as a get variable instead.

Gerben
  • 16,747
  • 6
  • 37
  • 56