m3div0
m3div0

Reputation: 1596

cross domain XHR

Hi I am facing a strange problem. I need to use webservice from different domain. So I looked into the code of chrome addon Simple REST Client and I have found out, that they are using this function to make XHR

function sendRequest() {
clearFields();
if ($("#url").val() != "") {
    var a = new XMLHttpRequest;
    a.onreadystatechange = readResponse;
    try {
        a.open($("input[type=radio]:checked").val(), $("#url").val(), true);
        //This code is for adding headers
        var b = $("#headers").val();
        b = b.split("\n");
        for (var c = 0; c < b.length; c++) {
            var d = b[c].split(": ");
            d[1] && a.setRequestHeader(d[0], d[1])
        }
        jQuery.inArray($("input[type=radio]:checked").val(), ["post", "put"]) > -1 ? a.send($("#postputdata").val()) : a.send("")
    } catch (e) {
        console.log(e);

        $("#responsePrint").css("display", "")
    }
} else {
    console.log("no uri");

}
}

So I have created similar one

    var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var test = $(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", "http://aplikace.mvcr.cz/sbirka-zakonu/SearchResult.aspx?q=1/2013&typeLaw=zakon&what=Cislo_zakona_smlouvy", true);
//xmlhttp.setRequestHeader('Access-Control-Allow-Origin','*');
 xmlhttp.send();

But with my code I am getting XMLHttpRequest cannot load http://aplikace.mvcr.cz/sbirka-zakonu/SearchResult.aspx?q=1/2013&typeLaw=zakon&what=Cislo_zakona_smlouvy. Origin http://localhost:51582 is not allowed by Access-Control-Allow-Origin. So where is the problem? Why the former code works and my doesn't even they are almost the same?

EDIT: I have also tried to call hte webservice with this function

$.ajax({
    type: "GET",
    url: "http://aplikace.mvcr.cz/sbirka-zakonu/SearchResult.aspx?q=1/2013&typeLaw=zakon&what=Cislo_zakona_smlouvy",
    contentType: "script; charset=utf-8",
    dataType: "jsonp",
    success: function (msg) {
        var tes = $(msg);
    },
    error: function (xhr, status, err) {
    }
});

and what I want to do is to read the response as DOM, because the webservice returns whole HTML page and I need only one div, but now I get Uncaught SyntaxError: Unexpected token < which points to this line

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

As I can see in the Network tab, the request works, but due to the error the success function is never called and I cant access the data.

Upvotes: 1

Views: 3843

Answers (3)

roberto
roberto

Reputation: 3563

As others have pointed out, this is due to the Same Origin Policy. This is something that is enforced by the browser, which means that an add-on can bypass this restriction. This should answer your initial question.

How to get around this? There are many ways, but most of them require some sort of cooperation from the server. People already mentioned some of those workarounds here and apparently you tried the JSONP path and got the error.

Why did you get the error? Because the script expected to get a response in JSONP format and it didn't: it got a HTML response instead. I think this approach won't work in your case, as the server definitely is not designed for this.

Now the real question is: why do you want to do this? Depending on your answer, I can think of several solutions.

For example, if you need to access the information from that page to be displayed on your website, the simplest solution, I believe, is to use some proxy (see http://developer.yahoo.com/javascript/howto-proxy.html for some more info).

If you're just using this on your own machine for personal purposes, it is possible in some browsers to specifically disable the same origin policy checks.

In Chrome, for example, running it with the following option will do the trick: (Warning: unsupported! Security will definitely suffer)

chrome --disable-web-security

If you do this (disable your browser's security checks), even a simple:

$.get("http://aplikace.mvcr.cz/sbirka-zakonu/SearchResult.aspx?q=1/2013&typeLaw=zakon&what=Cislo_zakona_smlouvy", function(data) {
    console.log(data);
},'html');

will work fine.

Upvotes: 1

slebetman
slebetman

Reputation: 113866

A browser addon/extension runs with different permissions and in a different environment from regular web pages. I suspect your code should work if made into an addon. It just won't work as a regular web page.

There are workarounds to this problem from CORS to proxying. Search for "cross domain ajax" here or google around.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Same Orgin Policy Prevents You From Doing It. Hence the error http://localhost:51582 is not allowed by Access-Control-Allow-Origin.

Upvotes: 1

Related Questions