Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

AJAX XML File

AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The following example demonstrates how a web page can retrieve information from an XML file using AJAX.

Example Explained

When the user clicks the “Get CD info” button, the loadDoc() function is triggered.

The loadDoc() function creates an XMLHttpRequest object, assigns the function to execute when the server response is ready, and sends the request to the server.

Once the server responds, an HTML table is generated, XML nodes (elements) are extracted, and the “demo” element is updated with the table filled with 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.lengthi++) {
    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;
}

The XML File

The XML file used in the above example is named “cd_catalog.xml”.