0

I'm writing a small program in JavaScript to read data from a local XML file. When I try to load this file, I get an error from IE9 saying:

SCRIPT5: Access is denied

When I try to load the same in Chrome, I get an error saying:

XMLHttpRequest cannot load file://... cross origin requests are only supported for HTTP

and

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file...

The following is my code:

<!DOCTYPE html>
<html>
<head>
    <h1 id="si">Search Input</h1>
    <button onclick="promptSearch()">Search By Vessel Name</button>
    <h1 id="sr">Search Result</h1>
<script>
    function loadXMLDoc(filename) {
        if (window.XMLHttpRequest) {
            xhttp=new XMLHttpRequest();
            }
        else { // for IE5 and IE6
            xhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        xhttp.open("GET",filename,false);
        xhttp.send();
        return xhttp.responseXML;
        }
    function promptSearch() {
        var prmpt = window.prompt("PLease enter vessel name:", "Vessel Name");
        var search= prmpt.toLowerCase();        
        if(prmpt != null){
            document.getElementById("si").innerHTML = search;
        }
        document.getElementById("sr").innerHTML = searchData();
    }   
    function searchData() {
        xmlDoc=loadXMLDoc("vesselData.xml");
    }
</script>
</head>
</html>
Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
BK14
  • 11
  • 3
  • Are you trying to run this Javascript from a local file instead of from an HTTP server? You can't use AJAX from a local file. – Barmar Oct 03 '14 at 03:53

1 Answers1

1

For security reasons, browsers don't allow JavaScript in a page to access local files around it, unless you run it on an HTTP Server.

You may use a simple HTTP Server, and your current issue will be resolved.

You can use nodejs to create a simple HTTPServer as shown here.

Community
  • 1
  • 1
Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
  • Thanks! With a bit of reformatting the issue went away. – BK14 Oct 03 '14 at 09:11
  • Was that supposed to be sarcastic or you really got it working on a local server? – Kamran Ahmed Oct 03 '14 at 09:33
  • Apologies, it seems that I deleted the line of code containing the 'send()' method, so the error did not arise anymore. I realised this when 'xhttp.responseXML' returned null. Thank you for your answer regarding the HTTP Server. So is there no way to access XML files locally using Javascript? – BK14 Oct 07 '14 at 03:05
  • No, there is no way to access any other local file through JavaScript without running it on a server. – Kamran Ahmed Oct 07 '14 at 04:21
  • Added a simple tutorial in the answer above to save your research time. – Kamran Ahmed Oct 07 '14 at 04:28
  • You may accept my answer if your query is resolved. :) – Kamran Ahmed Oct 08 '14 at 09:49