1

i want to show my .xml file on my html page in a table. So I wrote a javascript program to get the xml from the webserver and to create a table. But the HTTPRequest Response is always null, because the method onreadystatechange doesn't get called.

My javascript program

function LoadXML(dname) {
var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
} else {
    xhttp = new ActiveXObject('Microsoft.XMLDOM');
}
xhttp.onreadystatechange = function () {
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        return xhttp.responeXML;
    } else {
        return $("#errors").text("XML not found");
    }
};
xhttp.open("GET", dname, true);
xhttp.send(false);
}

function UpdateXML() {
xmlDoc = LoadXML('xml/history.xml');
var table = "<tr><th>Auftragsnummer</th><th>Auftraglaufzeit</th><th>Soll-Teile</th><th>Gutteile</th><th>Ausschussteile</th><th>OEE</th></tr>";
if (xmlDoc === null) {
    $("#errors").text("XML document is empty!");
} else {
    var x = xmlDoc.getElementsByTagName("Auftrag");
    for (i = 0; i < x.length; i++) {
        table += "<tr><td>" +
            x[i].getElementsByTagName("Auftragsnummer")[0].childNodes[0].nodeValue + "</td><td>" +
            x[i].getElementsByTagName("Aufnahmezeit")[0].childNodes[0].nodeValue + "</td><td>" +
            x[i].getElementsByTagName("TeileSoll")[0].childNodes[0].nodeValue + "</td><td>" +
            x[i].getElementsByTagName("Gutteil")[0].childNodes[0].nodeValue + "</td><td>" +
            x[i].getElementsByTagName("Ausschussteile")[0].childNodes[0].nodeValue + "</td><td>" +
            x[i].getElementsByTagName("OEE")[0].childNodes[0].nodeValue + "</td></tr>";
    }
}
document.getElementById("history").innerHTML = table;
setTimeout(updateTime, 5000);
}
window.addEventListener("load", UpdateXML);
Ollifred
  • 33
  • 7

1 Answers1

2

You are mixing async and sync code.

When you make an AJAX request, the code will continue its execution, and onreadystatechange will be called eventually. To retrieve the data you have to add a callback to your LoadXML function.

First you have to learn about sync and async functions and later read how to implement it to AJAX.

sync/async: What is the difference between synchronous and asynchronous programming (in node.js) (although it says node, is basically JavaScript)

AJAX examples: https://www.w3schools.com/js/js_ajax_examples.asp

Warning: If you go right to AJAX examples and just copy and paste code without learning the differences between async and sync, you will repeat this problem a lot in JavaScript.

Community
  • 1
  • 1
Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64
  • 1
    @Ollifred I'm glad :-) You can upvote/accept this answer then. Also, you must do it with all your questions with answers. Is the main point of this website and if you ratio is too low (0% right now), people will not help you in the future. – Jorge Fuentes González Mar 07 '17 at 19:15