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 https://www.youtube.com/watch?v=Dj3MP5w0dpc]

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.

Hide / Show Content: XML & DOM

Video tutorial illustrating the mechanism of hiding and unhiding / showing the XML content inside the DIV tag using DOM.

Before proceeding watch:

Display XML Data With DOM( innerHTML ): XML & Javascript

Business card Content
index.html

 Our Business Card!
   
   
Hide Email || Show Email

Here we get the element by its id and set its display style property to none, to hide it from the user. Later when the user clicks on Show link, we remove the display property none and leave it blank.

Video Tutorial: Hide / Show Content: XML & DOM


[youtube https://www.youtube.com/watch?v=CFoBb-4PJ8A]

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



Business card Styling
Style.css

.companyName
{
    font-family: Verdana;
    font-size: 18px;
    color: red;
    display: block;
    padding: 10px;
    margin: 20px;
    background-color: ivory;
    width: 400px;
    border: 5px;
    border-color: gray;
    text-align: left;
}

.Name 
{
    display: block;
    font-weight: bold;
}

.phone 
{
    display: block;
}

.company
{
    display:block;
}

.email
{
    display: block;
    color: Green;
}

This simple feature can be used to hide and unhide user profile information to the search boots or unauthorized users.
By default, set the email and other fields as hidden. Once the user is logged in or is a friend of the person whose profile is being viewed, then allow the person to access data via show function.

Read / Access XML Data With DOM: XML & Javascript

Video tutorial illustrating the manipulation of XML data using DOM [ Document Object Model ]

Using CSS Level 2, we couldn’t change the order in which we would display / access the XML data. To solve that and many more limitations, we make use of DOM.
In this tutorial you can learn, accessing the required XML content and arrange it as you need it.

Business card Content
index.html

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<html>
 <head><title>Our Business Card!</title>
 
  <script language="javascript" type="text/javascript">
 
  function display1() {
 
   var base    = document.getElementById("myBiz");
   var person1 = base.getElementsByTagName("companyName")[0];
   var name = "Name: " + person1.getElementsByTagName("Name")[0].firstChild.data;
   var phLable1 = person1.getElementsByTagName("phone")[0].getAttribute("type") + ": ";
   var phone1 = phLable1 + person1.getElementsByTagName("phone")[0].firstChild.data;
   var phLable2 = person1.getElementsByTagName("phone")[1].getAttribute("type") + ": ";
   var phone2 = phLable2 + person1.getElementsByTagName("phone")[1].firstChild.data;
   var email = "email: " + person1.getElementsByTagName("email")[0].firstChild.data;
   var company;
   comanyy = "Company: " + person1.getElementsByTagName("company")[0].firstChild.data;
 
   alert("Business Card: \n\n" + name + "\n" + phone1 + "\n" 
            + phone2 + "\n" + email + "\n" + company);
  }
 
 
 function display2() {
 
   var base = document.getElementById("myBiz");
   var person2 = base.getElementsByTagName("companyName")[1];
   var name = "Name: " + person2.getElementsByTagName("Name")[0].firstChild.data;
   var phLable1 = person2.getElementsByTagName("phone")[0].getAttribute("type") + ": ";
   var phone1 = phLable1 + person2.getElementsByTagName("phone")[0].firstChild.data;
   var phLable2 = person1.getElementsByTagName("phone")[1].getAttribute("type") + ": ";
   var phone2 = phLable2 + person2.getElementsByTagName("phone")[1].firstChild.data;
   var email = "email: " + person2.getElementsByTagName("email")[0].firstChild.data;
   var company;
   comapany = "Company: " + person2.getElementsByTagName("company")[0].firstChild.data;
 
   alert("Business Card: \n\n" + name + "\n" + phone1 + "\n" 
            + phone2 + "\n" + email + "\n" + company);
 }
 
  </script>
 
 </head>
 <body>
 
 <xml id="myBiz" style="display: none;">
 
 <companynames>
 
  <companyname>
    <name>Satish B</name>
    <phone type="home" primary="call me">(91) 9844552841</phone>
    <phone type="work">(91) 9844119841</phone>
    <email>[email protected]</email>
    <company>Technotip IT Solutions</company>
  </companyname>
 
  <companyname>
    <name>Shwetha</name>
    <phone type="home">(91) 123456789</phone>
    <phone type="work" primary="call me">(91) 987654321</phone>
    <email>[email protected]</email>
    <company>Microsoft</company>
  </companyname>
 
</companynames>
 
 
 </xml>
 
 <a href="javascript:display1()">Satish: Technotip IT Solutions</a><br />
 <a href="javascript:display2()">Shwetha: Microsoft</a>
 
 </body>
</html>

Here we’ve written entire thing in one file, for the purpose of demonstration.
We would highly recommend you to write javascript, css in external file and link it to the html file.

Video Tutorial: Read / Access XML Data With DOM: XML & Javascript


[youtube https://www.youtube.com/watch?v=pJiJWWKEbU0]

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



First we fetch the root tag and assign it to a javascript variable called base. Using this as a reference, we fetch the sub-element and using which we fetch all its child elements and inturn get the data present inside them.

Remember, the string inside the tags Name, phone email and company is also considered separate node.

Inside the index.html file we have taken two anchor tags:
Satish: Technotip IT Solutions
Shwetha: Microsoft

which invoke the javascript functions and then display the information of respective people.

If in case we have hundreds or thousands of people in our XML file, we could use looping and dynamically fetch XML data and display it more meaningfully and with less effort(due to proper programmatical automation).

Business Card Design: XML & CSS Level 2

Video tutorial to show the design of business cards using XML and Cascading Stylesheet Level 2.

Continuing the tutorial from previous day: Business Card Design: XML & CSS

In the previous tutorial there was no facility to display the labels using CSS.
To over come that problem, we step into CSS Level 2, wherein we include the label information to the presentation layer using CSS level 2 coding.

Business card Content
companyNames.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
< ?xml version="1.0" encoding="utf-8"?>
< ?xml-stylesheet type="text/css" href="Style.css" ?>
<companynames>
 
  <companyname>
    <name>Satish B</name>
    <phone type="home" primary="call me">(91) 9844552841</phone>
    <phone type="work">(91) 9844119841</phone>
    <email>[email protected]</email>
    <company>Technotip IT Solutions</company>
  </companyname>
 
  <companyname>
    <name>Shwetha</name>
    <phone type="home">(91) 123456789</phone>
    <phone type="work" primary="call me">(91) 987654321</phone>
    <email>[email protected]</email>
    <company>Microsoft</company>
  </companyname>
 
 
</companynames>

There is no change with the companyName.xml file.
To know more details, please visit Business Card Design: XML & CSS

Business card Styling Information + CSS Level 2 coding
Style.xml

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
40
companyName
{
    font-family: Verdana;
    font-size: 18px;
    color: red;
    display: block;
    padding: 10px;
    margin: 20px;
    background-color: ivory;
    width: 400px;
    border: 5px;
    border-color: gray;
    text-align: left;
}
 
Name 
{
    display: block;
    font-weight: bold;
}
 
phone 
{
    display: block;
}
 
company
{
    display:block;
}
 
email
{
    display: block;
    color: Green;
}
 
email:before { content: "email: " }
phone:before  { content: attr(type) ": " }
phone[primary]:after { content:"(" attr(primary) ")" }

Last 3 lines of coding is the only thing changed from previous day tutorial.
Those 3 lines are CSS Level 2 coding!

using :before pseudo class selector we tell the parser to include email: as content before displaying the actual email id.

similarly, using :after we include the label after the actual content.

attr(type) this selects the value assigned to the attribute type from companyNames.xml file and displays it.
phone[primary]:after There are multiple phone numbers, one of which is made primary. So phone[primary] points to the phone number which has the attribute primary.

Video Tutorial: Business Card Design: XML & CSS Level 2


[youtube https://www.youtube.com/watch?v=GHNx22hRwwM]

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



I’ve shown CSS Level 2 working on all 3 browsers: Internet Explorer, Mozilla Firefox and Google Chrome.
But some older versions of Internet Explorer doesn’t support CSS Level 2 coding.
To solve this issue( cross browser compatibility issue ), we can make use of XSLT [ eXtensible Stylesheet Language Transformations ]. We’ll see it in coming video tutorials.

Output on the browser
Satish B
home: (91) 9844552841(call me)
work: (91) 9844119841
email: [email protected]
Technotip IT Solutions

Shwetha
home: (91) 123456789
work: (91) 987654321(call me)
email: [email protected]
Microsoft


Business Card Design: XML & CSS

Video tutorial to show the design of business cards using XML and Cascading Stylesheet.

In this example we apply styling to business cards of two people.
The primary information i.e., the content is in XML and the presentation is taken care by CSS.

Base tag or the root tag name is companyNames
and the elements inside root tag is companyName
Other tags present inside companyName tag are Name, phone, email, company.

Example:
Two people are Satish B and Shwetha, they are working in Technotip IT Solutions and Microsoft respectively.

Business card Content
companyNames.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
< ?xml version="1.0" encoding="utf-8"?>
< ?xml-stylesheet type="text/css" href="Style.css" ?>
<companynames>
 
  <companyname>
    <name>Satish B</name>
    <phone type="home" primary="primary">(91) 9844552841</phone>
    <phone type="work">(91) 9844119841</phone>
    <email>[email protected]</email>
    <company>Technotip IT Solutions</company>
  </companyname>
 
  <companyname>
    <name>Shwetha</name>
    <phone type="home">(91) 123456789</phone>
    <phone type="work" primary="primary">(91) 987654321</phone>
    <email>[email protected]</email>
    <company>Microsoft</company>
  </companyname>
 
 
</companynames>

This file has already been connected to a external stylesheet.

Business card Styling Information
Style.xml

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
companyName
{
    font-family: Verdana;
    font-size: 18px;
    color: red;
    display: block;
    padding: 10px;
    margin: 20px;
    background-color: ivory;
    width: 300px;
    border: 5px;
    border-color: gray;
 
 
}
 
Name 
{
    display: block;
    font-weight: bold;
}
 
phone 
{
    display: block;
}
 
company
{
    display:block;
}
 
email
{
    display: block;
    color: Green;
}

Here we make all the elements display as block. Next add some padding and margin..and a light background color.

Video Tutorial: Business Card Design: XML & CSS


[youtube https://www.youtube.com/watch?v=cb3vZ08H3Hw]

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



output on browser

Satish B
(91) 9844552841
(91) 9844119841
[email protected]
Technotip IT Solutions

Shwetha
(91) 123456789
(91) 987654321
[email protected]
Microsoft