AJAX XML File

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

AJAX XML File

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

Example

<!DOCTYPE html>

<html>

<style>

table,th,td {

  border : 1px solid black;

  border-collapse: collapse;

}

th,td {

  padding: 5px;

}

</style>

<body>

<h2>The XMLHttpRequest Object</h2>

<button type=”button” onclick=”loadDoc()”>Get my CD collection</button>

<br><br>

<table id=”demo”></table>

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

</body>

</html>

Example Explained

When a user clicks on the “Get CD info” button above, the loadDoc() function is executed.

The loadDoc() function generates an XMLHttpRequest object, adds the function to be executed as soon as the server response is ready, and sends the request off to the server.

When the server response is ready, an HTML table is created, nodes (elements) are extracted from the XML file, and it updates the element “demo” with the HTML table filled with XML data:

Example

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;

}