Reading XML File Using jQuery AJAX Method


Video tutorial to read XML file using jQuery ajax method.

AJAX full form: Asynchronous JavaScript and XML
We’ll also see the use of setTimeout() function.

Using AJAX technique, we fetch only the required data from the server without reloading the entire page.

In this video tutorial, we fetch the data present in XML format and display fetched content on the webpage and update it in real time, without reloading the html page.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head><title>Reading an XML file using jQuery</title></head>
<body>
 
 <ul></ul>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 1 ul tag. We’ll load the list items dynamically using jQuery, from XML file.

XML File Content
corporateData.xml

1
2
3
4
5
6
7
8
9
< ?xml version="1.0" ?>
 
<corporate>
 <employee>
  <name>Satish</name>
  <age>25</age>
  <company>Microsoft</company>
 </employee>
</corporate>

Here we have a base tag called corporate. Inside that we have employee details like name, age and company which is bound inside employee tag. Each employee will have his/her details inside separate/individual employee tag.

For more about XML, please visit XML category.

jQuery File: corporateData() function
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
     });
}

Here we write a custom jQuery function called corporateData.
$.ajax() is a jQuery static method and it has a lot of properties. In this tutorial, we illustrate url, dataType, success and error properties.
Specify the url from which the data has to be fetched, along with its data type.
If the file gets parsed successfully, the function inside the success property gets executed. If there is an error, the error property function gets triggered.

Once the xml file gets parsed successfully, $.ajax method throws an object which contains xml file data. We catch this data with anonymous function present in success property.
Next, we clear any previous data got attached to the unordered list of html document.

Using the object, we find each employee tags present inside the XML file, fetch individual name, age and company names and then append it to the unordered list.

jQuery File: setTimeout() method
my_script.js

1
2
3
4
5
6
7
8
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}

Inorder to make sure our application fetches the fresh data from the XML file, we check the XML file after certain period of time.
Using setTimeout() method of jQuery:
setTimeout() takes two parameters, first one being the function names to be called and the second one being the time interval after which those functions has to be called.

using setTimeout() we have called itself( fetch() ) and corporateData() function. This makes sure, whenever the XML file gets updated, our application fetches the data and displays on our webpage, without refreshing the page.

jQuery File: call the functions to make it work
my_script.js

1
2
3
4
$(document).ready( function() {
 corporateData();
fetch();
});

Make sure to call both corporateData and fetch method once the page loads. This makes sure the XML data is fetched before fetch functions tries to re-fetch the things.

jQuery File: Complete Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$(document).ready( function() {
 corporateData();
fetch();
});
 
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}
 
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
});
}

corporateData.xml and index.html files must be in the same folder.

Video Tutorial: Reading XML File Using jQuery AJAX Method



YouTube Link: https://www.youtube.com/watch?v=Dj3MP5w0dpc [Watch the Video In Full Screen.]



Note:
Make sure you open the html file from a server(even from localhost), and not directly from a folder. XML and the files which are fetching XML data must be on the same server, otherwise XML data won’t be fetched.

Testing The Application
To test this small application, open the index.html file from the server, and then add / modify / delete any entry. Once you save the XML file, the content of XML file must get updated on the html file immediately without the page(index.html) being reloaded.

10 thoughts on “Reading XML File Using jQuery AJAX Method”

  1. Excellent article and video. Exactly what I was looking for. Thanks!

    One small comment. The statement setting the variable “info” in my_script.js is missing a single quote and a plus at the end of the first two lines, and a single quote at the beginning of the second two lines.

    1. Thanks for your feedback @Craig,

      Those single quotes and plus are correct, I’m just introducing line breaks inorder to make it more human readable. Copy it into a plain text editor and remove the new lines and you’ll see those single, double, plus symbol combination are correct!

      Am really happy to know that this Video tutorial and notes helped you :-)

  2. Hello. Nice Tut. I have implemented it in a script but I notice that after a few seconds it seems to time out. I will make changes to my xml file but they will not post until I refresh. Any thoughts?

    1. Make sure to check these line of code:

      1
      2
      3
      4
      
      setTimeout( function() {
       corporateData();
      fetch();
      }, 100);

      See the time interval and the functions you’re calling are working properly. Check their outputs without ajax, if everything works, then implement AJAX using jQuery.

      Follow the video tutorial: Type along with me and check for the results.

      Happy coding ..

      1. Satish,

        Got it. This is working fine. I feel like it is something to do with the setTimeout function freaking out the DOM. Like after 50000 milliseconds it just fails. Perhaps there is a way to reset the timer?

        Further. When I try to work with the elements, developing UI features like clickablilty etc. The constant refreshing causes animate() and other functions to act erratically. thoughts?

        D

  3. Hello my friend,
    Nice tutorial but i have one question why the url from which the data has to be fetched can’t be a url from another server like http :// www . another_website . com?????

    1. @Chris, That is how XML is supposed to work. It was implemented for security reasons. However you can over come it by making use of JSONP – by developing API’s.

  4. May I ask you anything more?
    How can I execute some commands when a variable like “name = +$(this).find(“name”).text()”
    changes from xml file?

    Thanks Satish…

Leave a Reply

Your email address will not be published. Required fields are marked *