I am creating a website that relies on the data of an XML file hosted on a separate domain. In short, if an element in the XML file hosted on HTTP://example.com/test.XML changes from true to false, I want an element of the HTML file on my domain to change. I can achieve this if the XML is in the same directory as my HTML file but I cannot find a solution to the problem of it being on a different domain.
I have tried to use jquery but I am not sure what I am doing wrong. The code I have tried looks like:
$(document).ready(function(){
var myXML = ""
var request = new XMLHttpRequest();
request.open("GET", "http://example.com/test.XML", true);
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
myXML = request.responseXML;
}
}
}
request.send();
document.getElementById("test").innerHTML = new XMLSerializer().serializeToString(myXML.documentElement);
});
Please help, and thank you in advance for your time!
Try using the not so recent fetch api.
$(document).ready(function(){
var myXML = ""
fetch("http://example.com/test.XML")
.then( response => response.text() )
.then( response => {
//response is a string containing xml...
document.getElementById("test").innerHTML = response
})
.catch( console.error )
;
});
I thing you don't need to serialize the xml, you should just be able to put it directly... but not sure
Your code seems to be working perfectly, thanks. However, I am still receiving an error, can you help me find a way around this?
The error I am receiving is as follows: Access to fetch at 'example.com/test.xml' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
You make an api to a different domain (that the one for the app, even if it just differs by port) so browser have protection mechanisme to be sure your app can request this API. It is call Cors. just read a bit about it