AJAX XML Example


You can employ AJAX to interactively communicate with an XML file.


AJAX XML Example

Here's a simple example to show how a webpage can get data from an XML file using AJAX:


Example Explained

When someone taps the "Get CD info" button, the loadDoc() function runs.

The function loadDoc() makes a special object called XMLHttpRequest. It also attaches a function to run when the server replies and then sends the request to the server.

Once the server sends a response, a table in HTML is created. Elements are taken from the XML file and used to fill this HTML table. Finally, the "demo" element is updated with the table containing the XML data.

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;
}