1

I am just learning AJAX and trying out the same simple example that is here.

I have created a folder called ajax-first-try and created a html file called test.html. The following are the contents of the html.

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <h1>The page loads first</h1>
    <h2>If you click the below button i will load the data in an xml without reloading the page.</h2>
    <button onclick="loadTable()">click</button>
    <div id="demo"></div>
</body>
<script type="text/javascript">
    function loadTable() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if(this.readyState == 4 && this.status == 200) {
                printTable(this);
            }
        };
        xmlhttp.open("GET", "cd_catalog.xml", true);
        xmlhttp.send();
    }

    function printTable(xmlhttp) {
        var table = "<tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th></tr>";
        <!-- code that adds rows to table -->
        document.getElementById("demo").innerHTML = table;
    }
</script>
</html>

The same folder contains the xml called cd_catalog.xml whose contents are this.

When I click the button, I get the following error. I understand that this is a standard error, and there are already many questions about this error. But I am not able to understand them as they are complex use case/solution.

test.html:21 Access to XMLHttpRequest at 'file:///Users/arun-8076/Desktop/javascript/ajax-first-try/cd_catalog.xml' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. loadTable @ test.html:21 onclick @ test.html:9

subject-q
  • 91
  • 3
  • 19
  • 1
    You can not access from local. I searched and tried at command line `chrome --disable-web-security -–allow-file-access-from-files` but did not success. You must host your file like w3school – Hien Nguyen Apr 10 '19 at 05:23
  • 1
    Trying to access your file using the local file system doesn't work in your case. Origin is null because it's your local file system. Try to run from visual code using Live server extension. It will not give you CORS error – Ritesh Singh Rajput Apr 10 '19 at 05:29
  • The question that already had answer did not come in my search results. Thankfully someone put it her. I hosted it in tomcat. and now it is working. – subject-q Apr 10 '19 at 05:29

0 Answers0