Reading time: 2 minutes
Good afternoon, everyone,
We continue with JavaScript tutorials. Today, I’m going to show you how to make an AJAX call in JavaScript to access data from an XML file.
You might be wondering, what is AJAX?
In a quick, clear, and concise manner, AJAX is a web development technique that allows you to retrieve data from a server after the page has loaded, update a web page without reloading the browser, and send data to the server in the background.
Let’s move on to the example:
You can find this XML file at: https://www.w3schools.com/
<?xml version="1.0" encoding="UTF-8"?> <CATALOG> </CATALOG>
And here’s the AJAX code I’ve created for the example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>devcodelight</title> <script> // Common header for any JavaScript AJAX call var request = ""; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); } else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); } // Function called on button click function ajaxRequest() { request.onreadystatechange = showContent; request.open("GET", "cd_catalog.xml", true); request.send(null); } // Display the data on button click function showContent() { if (request.readyState == 4 && request.status == 200) { var text = ""; var catalogInfo = request.responseXML; var title, artist, year; var cds = catalogInfo.getElementsByTagName("CD"); for (var i = 0; i < cds.length; i++) { title = catalogInfo.getElementsByTagName("TITLE")[i].firstChild.nodeValue; artist = catalogInfo.getElementsByTagName("ARTIST")[i].firstChild.nodeValue; year = catalogInfo.getElementsByTagName("YEAR")[i].firstChild.nodeValue; text += "Title: " + "<font color ='blue'>" + title + "</font>" + "<br>"; text += "Artist: " + "<font color ='blue'>" + artist + "</font>" + "<br>"; text += "Year: " + "<font color ='blue'>" + year + "</font>" + "<br>"; text += "<br>" } document.getElementById("myDiv").innerHTML = text; } } </script> </head> <body> <h1>Ajax Devcodelight</h1> <form name="myForm"> <input type="button" value="Show Data" onclick="ajaxRequest();"> <div id="myDiv"></div> </form> </body> </html>
If you have any questions, feel free to leave your comment.
Here’s the result of what our AJAX displays:
In the next tutorial, I’ll show you another AJAX example, but this time accessing data from different XML files depending on the option selected in the dropdown.
As always, I hope you like it, but most importantly, I hope it’s helpful. :slightly_smiling_face: