I've made various attempts to load XML
from external servers, but without success.
The first example loads the XML
perfectly when I have the XML document
on my server, but not when I try loading the same XML
from the external server.
The second example is loading XML
from on an external server, but the data that loads on my page doesn't resemble XML.
Am I missing something in my XMLHttpRequest
, or is this the Cross Origin
problem?
EDIT: The second example was solved by changing responseText
to responseXML
, however the first example already has responseXML
and yet it doesn't work. Why won't the first example function in the same manner as the second example?
first example
var n = document.getElementById("search");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET","https://www.w3schools.com/xml/books.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
var a = n.value;
var xmlDoc = xhttp.responseXML;
const { value } = search;
const foundState = [...xmlDoc.querySelectorAll('title')].find(possibleMatch => possibleMatch.textContent === value);
const unit = foundState.parentElement;
console.log(unit.innerHTML);
document.getElementById("titleNode").innerHTML = unit.children[0].textContent;
document.getElementById("authorNode").innerHTML = unit.children[1].textContent;
document.getElementById("yearNode").innerHTML = unit.children[2].textContent;
}
<input type="text" name="search" id="search" placeholder="type 'r'" list="searchresults" autocomplete="off" />
<datalist id="searchresults">
<option value="Everyday Italian">001</option>
<option value="XQuery Kick Start">010</option>
<option value="Learning XML">110</option>
<option value="Harry Potter">101</option>
</datalist>
<button id="myButton" type="button"
onclick="loadDoc('https://www.w3schools.com/xml/books.xml', myFunction)">Submit
</button>
<p>Title node: <span id="titleNode"></span></p>
<p>Author node: <span id="authorNode"></span></p>
<p>Year node: <span id="yearNode"></span></p>
second example
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", "https://data.cityofnewyork.us/api/views/kku6-nxdu/rows.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseXML;
}
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button"
onclick="loadDoc('ajax_info.txt', myFunction)">Change Content
</button>
</div>