JavaScript AJAX XML File
JavaScript Basics

JavaScript AJAX XML File

AJAX XML Example

AJAX can be utilized 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:

Get CD Info

Example Explained

When the user clicks on the "Get CD Info" button, the loadDoc() function is executed.

The loadDoc() function does the following:

  1. Creates an XMLHttpRequest object.
  2. Assigns a function to be executed when the server response is ready.
  3. Sends the request to the server.

Once the server response is ready, the function builds an HTML table, extracts nodes (elements) from the XML file, and updates the element with id "demo" with the HTML table filled with XML data.

JavaScript Code:

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

The XML File

The XML file used in the example above is named cd_catalog.xml and contains the data to be fetched and displayed.

Take a look into your desired course