How can we fetch information from XML file using AJAX

We can fetch and collect information of XML file using AJAX. In it first a function creates an object and then adds a function which is to be executed and when the server response is ready, sends the request off to the server.

<script>
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    myFunction(this);
  }
  xhttp.open("GET", "cd_catalog.xml");
  xhttp.send();
}
function myFunction(xml) {
  const xmlDoc = xml.responseXML;
  const x = xmlDoc.getElementsByTagName("CD");
  let table="<tr><th>Artist</th><th>Title</th></tr>";
  for (let i = 0; i <x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</script>

The loadDoc() function creates an XMLHttpRequest object, it adds the function which is to be executed. And when the server response is ready, it sends the request off to the server.

Leave a comment

Your email address will not be published. Required fields are marked *