How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

I’m going to share some tricks about XML file and APIs processing. I will also demonstrate how a web page can fetch information from an XML file in JavaScript using JQuery AJAX.

Assumptions: for the purpose of this article, I’m going to assume that you have good understanding and knowledge of JavaScript, the XML file format, and jQuery. If not please find documentation here to learn more details about it.

The project I worked on recently consisted of processing XML data resulting from an API call. The resulting XML data *file was very large and its content is private data that I can’t share. *So in this post, I will show you how to process an *XML demo ***file.

Below is the sample XML file from w3chools that I’ll be using for the demo:

<?xml version="1.0" encoding="UTF-8"?>


    <breakfast_menu> 

       <food> 
           <name>Belgian Waffles</name> 
           <price>$5.95</price> 
           <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> 
           <calories>650</calories> 
       </food> 

       <food> 
           <name>Strawberry Belgian Waffles</name> 
           <price>$7.95</price> 
           <description>Light Belgian waffles covered with strawberries and whipped cream</description> 
           <calories>900</calories> 
       </food> 

       <food> 
           <name>Berry-Berry Belgian Waffles</name> 
           <price>$8.95</price> 
           <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 
           <calories>900</calories> 
       </food> 

       <food> 
           <name>French Toast</name> 
           <price>$4.50</price> 
           <description>Thick slices made from our homemade sourdough bread</description> 
           <calories>600</calories> 
       </food> 

       <food> 
           <name>Homestyle Breakfast</name> 
           <price>$6.95</price> 
           <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 
           <calories>950</calories> 
       </food> 

    </breakfast_menu>

Now, create a folder for the demo project and save the demo.xml file in it. I named mine “XML-demo”. Inside your project folder, create a JavaScript file and HTML file that will display the data (index.html and main.js). I’m not using a separate CSS file for styling.

I recommend using *Visual Studio Code IDE for this demo and in your VS Code install Live Server extension.* The following is a screenshot of my demo folder opened in VS code:

VS Code IDE Screenshot — shows files

Next step is adding your script and jquery-UI references in your index.html and define how you would like to display data. I’m simply displaying data in a “ul” element. Here’s how my index.html looks like:

<!DOCTYPE html>
    <html lang="en">


        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>XML-Jquery</title>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">


            <!-- **************************************************************************************** 
            !   connect your main.js script to hmtl                                                     *
            !   add version of jquery                                                                   *
            ! *************************************************************************************** -->
            <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


            <!-- javascript reference -->
            <script type="text/javascript" src="./main.js"></script>
        </head>


        <body>
            <div class="container">
                <div class="jumbotron" style="text-align: center;">
                    <h1 id="headerTitle">Food Menu List</h1>
                </div>


                <ul></ul>


            </div>
        </body>


    </html>


    <!-- ****************************************** END **********************

Reading XML

So the basic method for doing asynchronous calls in jQuery is the AJAX() function, documented here. That documentation has a lot going on but that should get you started and help you walk through my main.js script to understand how the XML file is processed through AJAX:

// Do some stuff when page hmtl page is launched
    $(document).ready(function () {


        $("#headerTitle").hide(300).show(1500);
        // calling show food menu function
        showFoodMenu();

        // If you want to fetch data from the file 
        // call fetch data function instead of showFoodMenu
        // fetchData()
    });


    // ***************************************************************************************
    // this function calls showfoodmenu 3000 milisecond to get new changes                   *
    // made on demo.xml                                                                      *
    // ***************************************************************************************
    function fetchData() {
        setTimeout(function () {
            showFoodMenu();
            // recursive call
            fetchData();
        }, 3000);
    }


    // **************************************************************************************
    // read data from demo.xml using Jquery | AJAX                                          *
    // **************************************************************************************
    function showFoodMenu() {


        $.ajax({
            type: "GET",
            url: "./demo.xml",
            dataType: "xml",


            error: function (e) {
                alert("An error occurred while processing XML file");
                console.log("XML reading Failed: ", e);
            },


            success: function (response) {


                // make sure the ul is empty
                // before appending data inot it
                $("ul").children().remove();


                $(response).find("food").each(function () {
                    var _name = 'Name: ' + $(this).find('name').text();
                    console.log(_name);

                    var _price = 'Price: ' + $(this).find('price').text();
                    var _calories = 'Calories: ' + $(this).find('calories').text();
                    var _description = 'Description: ' + $(this).find('description').text();


                    // add content to the HTML          
                    $("ul").append('<li>' + _name + '</li>');
                    $("ul").append('<li>' + _price + '</li>');
                    $("ul").append('<li>' + _calories + '</li>');
                    $("ul").append('<li>' + _description + '</li>');
                });
            }
        });
     }
You should have the icon for Go live on your VScode IDE if you successfully install [***Live Server***](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer "***Live Server***") extension. Clicked to Go Live icon on the right bottom of your VS code IDE or simply right click on HTML file and select “open with Live Server”. if you followed exactly and correctly what I did, you should get this:

Final result — Displaying XML data on HTML

Tips

Do not put the script reference to jquery-UI before the jquery script itself on your HTML otherwise you’ll get this error: *Uncaught ReferenceError: $ is not defined. *Make sure your script is referenced after you have referenced jquery-UI as I did in my main.js script.

Frequently used acronyms* API: Application programming interface

  • Ajax: Asynchronous JavaScript
  • CSS: Cascading Stylesheets
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • RSS: Really Simple Syndication
  • SGML: Standard Generalized Markup Language
  • SVG: Scalable Vector Graphics
  • URI: Uniform Resource Identifier
  • URL: Uniform Resource Locator
  • W3C: World Wide Web Consortium
  • XHTML: Extensible Hypertext Markup Language

If you enjoyed this story, you might also like “How to Set Up the Development Environment

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

There are two functions to deal with an array on the client-side – JavaScript's .forEach() and jQuery's .each(). Here, I will teach you how to use both of these methods with some sample code.

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? jQuery vs vanilla JavaScript - Beau teaches JavaScript

3 JavaScript libraries to replace jQuery

Ubiquitous jQuery has been outmoded by JavaScript and browser advances. Cash, Zepto, and Syncfusion are three JavaScript libraries picking up where jQuery left off