1

I have this script that fetches information form a XML file. It works fine in W3schools Tryit Editor but not when I have it locally run on my pc. (When run on the W3 editor, you need to change questions.xml to books.xml and qtext to title.)

I copied books.xml from w3schools to test if my .xml file was bad but the script didn't work locally with books.xml either.

I have found people having similar problems but it was always due to them referencing to something in a different domain which I am aware isn't supposed work but my problem shouldn't have anything to do with that. I have tried googling further but it's hard to get google to find anything close to the search terms.

Here's the code:

<p id="xmltesti">asd</p>

<script>
var xhttp = new XMLHttpRequest(); //Create variable for XMLHttpRequest
xhttp.onreadystatechange = function() { //When readyState property changes, run function
    if (this.readyState == 4 && this.status == 200) { //If everything is OK
        getText(this); //Run function GetData ("this" refers to the parent object)
        console.log("Everything OK!");
    } else {
        console.log("Problems occurred!");
        console.log(xhttp.status);
    }
};
xhttp.open("GET", "questions.xml", true);
xhttp.send();

function getText(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById("xmltesti").innerHTML =
    xmlDoc.getElementsByTagName("qtext")[0].childNodes[0].nodeValue;
}
</script>

The browser console looks like this (I am also wondering why it prints it twice):

Problems occurred!  
0  

Problems occurred!  
0

Edit: I uploaded the files to my web server and it is now working. Problem partly solved. But it is easier to test it on my local machine than constantly having to upload files to the server. And I'd also like to know why it doesn't want to upload when I run it on my local machine.

agaboy6000
  • 29
  • 6
  • 3
    You can't use AJAX with file protocol. If you need this to run in a local machine, you've to set up a local server. [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) says, that "_protocol, port (if specified), and host are the same_", "file" is not same as "http", which is the protocol XMLHttpRequest uses. – Teemu Feb 28 '20 at 12:45
  • Ok, thanks. Makes sense and that explains why it worked when I uploaded the files to my web server. I feel stupid for not testing them on the web server before asking. And very nice that you didn't vittuilla like many people on here do when you ask something. Could you post your comment as an answer so I will upvote you and mark it as an answer? – agaboy6000 Feb 28 '20 at 12:47
  • Please note that W3Schools has absolutely nothing to do with W3C. – Michael Kay Feb 28 '20 at 14:37
  • Thanks for the info, didn't know that. Though what does it have to do with this case? – agaboy6000 Mar 04 '20 at 07:57

0 Answers0