16

I am getting the following error: jquery ajax readystate 0 responsetext status 0 statustext error when giving it: url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm), however it's working fine when I give it url(localhost:""/embparse_page) on my localhost.

I have tried using the headers which I found on a Google search, and I have used beforeSend:"" too, but it's still not working.

I think the main problem is: XMLHttpRequest cannot load http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm. Origin "local server" is not allowed by Access-Control-Allow-Origin. but I don't understand it.

Can anyone please explain the problem to me, as I'm quite new to this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:ng="http://angularjs.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta Access-Control-Allow-Origin="*" />
    <title>Page Parsing</title>
    <script type="text/javascript" src="/js/jquery-1.9.1.min.js"></script>
    <script>
    getit=function(){
        jQuery.support.cors = true;
        $.ajax({
            type:"GET",
            url:"http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm",
            dataType:"html",
            crossDomain:true,
            beforeSend: function(xhr) {
                xhr.overrideMimeType('text/plain;charset=UTF-8');
            },
            success:function(XMLHttpRequest,jqXHR ,data) {
                //alert(data.title);
                var starttitl=data.lastIndexOf('<title>');
                var endtitl=data.lastIndexOf('</title>');
                var title1=data.substring(starttitl+7,endtitl);
                alert(title1);
            },
            error:function(errorStatus,xhr) {
                alert("Error"+JSON.stringify(errorStatus));
            }
        });
    }   
    </script>
</head>
<body>
    <div id="siteloader">
        <input type="button" onclick="getit()" />
    </div>
</body>
</html>
Dave
  • 498
  • 2
  • 7
  • 22
Dhirender Tyagi
  • 315
  • 1
  • 3
  • 10
  • 5
    One tip: don't use alert as it's the most irritating way to debug. Try `console.log` and press F12 in Chrome or control + shift + k in firefox to open the console. You have a lot of tools in there that you can use like setting breakpoints and inspecting requests with their request and response headers. – HMR Oct 16 '13 at 05:45
  • The top rated answer on this post is pretty in depth: http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-ajax – Adrian Oct 21 '16 at 05:26
  • 3
    @HMR, without alerts, what do you suggest if you're testing on an iOS device and you don't have a mac to do any kind of remote debugging? – Ads Jan 14 '19 at 23:27

5 Answers5

21

I was getting this error and in my case it was not due to same origin policy. I got some help from this link. Other possible reasons can be seen in here.

My case was, I had a link button and I was not using e.PreventDefault()

ASPX

<asp:LinkButton ID="lnkSearch" runat="server" CssClass="DockCmdSearch" CommandName="Search" OnClientClick="return VerifySearch(this, event);" />

Javascript

function VerifySearch(sender, e) {        
    e.preventDefault();
    $.ajax({
                type: 'POST',
    .............
    }
    return false;
}
user007
  • 1,504
  • 2
  • 18
  • 51
  • The top rated answer on this post is pretty in depth: http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-ajax – Adrian Oct 21 '16 at 05:26
0

same origin policy. the browser does not allow when you're on

http://site1.com

to connect to:

site2.com
sub.site1.com
site1:99.com
https://site1.com (not sure about this one)

This is so site1 cannot steal content from site2 and pretend it's the content of site1. Ways around this is JSONP (google maps use that I think) and having site2 provide cors headers but cors are not supported in jQuery 1.* (maybe not in 2.* either) because IE has some problems implementing it. In both situations you need site2 to cooperate with your site so your site can display it's content.

If you only use this yourself then you can use Firefox and install the forcecors plugin. To activate you can choose view => toolbars => add on bar and click on the text "cors" in the right bottom of the screen.

HMR
  • 37,593
  • 24
  • 91
  • 160
  • But we can do this concept(can access the content of site2 from site1) in php by using cURL(). So if there is something like that in javascript plz tell me – Dhirender Tyagi Oct 16 '13 at 06:37
  • Yes, you can proxy requesrs through your server but you're violating the ip property of the site you're getting your content from. Some big supermarket site did this and when the other site detected it they fed the supermarket site bogus info with pictures of cut off heads and the likes. This was a playful and effective way,it could also be a lawyer knocking on your door – HMR Oct 16 '13 at 10:33
  • @DhirenderTyagi The proxying through php is an option if site2 doesn't want your site to display it's content or wants to but doesn't care enough to create a JSON API. This can't be done in JavaScript because JavaScript runs in the browser and it's the browser that enforces the same origin policy to protect sites from having their content taken and presented on other sites. At least with the proxy method site2 can detect a lot request coming from the same IP. – HMR Oct 16 '13 at 14:15
  • Same Origin Policy is not for the protection of intellectual property. It is overall a security feature. More info here: http://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important – Andy Groff Jul 23 '14 at 14:39
0

I was getting that error from my Ajax call, and what fixed it for me was just putting in the 'return false'.

BlooSki
  • 79
  • 6
0

I had same problem with Nginx ( server side ) and AngularJs ( User side )
as other developer said its Cors problem , here i just want to say how i solve my problem maybe some one use this approach ;)
first I added below lines to my Nginx config files( in linux -> /etc/nginx/sites-available/your domain) :

    add_header Access-Control-Allow-Origin *;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

and with angularJs I send my request like this :

        $http({
            method: "POST",
            data: { //params},
            url: "//address",
            headers: { //if its form data
                "Accept": "application/json",
                "Content-Type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-cache"
            },
            crossDomain: true,
            contentType: false,
            processData: false
        }).then(function mySucces(response) {
            alert(JSON.stringify(response));
        }, function myError(response) {
            alert("error");
        });
Mhmd
  • 406
  • 5
  • 12
-3

I was testing reading a txt/XML file for json/xml data and got an error... the values read: Status[0] & readyState[0] and StatusText[error]; This was working successfully on Internet explorer but not on Chrome because the domain needed to be the same

This is what fixed it

Go to C:\WINDOWS\system32\drivers\etc\hosts

Put a name against your localhost app:

127.0.0.1   SampleSiteName.com

Now open the code in chrome as http://SampleSiteName.com/YourAjaxFileName.htm (if it opens, it means that you have entered a host name correctly) go to your HTML file and give a relative address of the file which you are trying to read (if FileToBeRead.txt is in the same folder as YourAjaxFileName.htm, then just enter url: "/FileToBeRead.txt")

Now your code will work on Chrome as well.

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
  • I don't see how this could get content from a remote site. Your ajax request would just loop back to your local machine because it would resolve the remove domain name to 127.0.0.1. – Adrian Oct 21 '16 at 05:24
  • 1
    On stackoverflow, to make a new line in your post, you have to either use `
    ` or make 2 new lines. See my edit.
    – Ali Bdeir Oct 21 '16 at 05:37
  • whoops sorry it is late for me – Adrian Oct 21 '16 at 06:24