Parsing XML with JQuery without adding plugin

jQuery is great library for developing ajax based application. jQuery is great library for the JavaScript programmers, which simplifies the development of web 2.0 applications.

You can use simple JavaScript to perform all the functions that jQuery provides. Then why jQuery? The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

jQuery Plugin: jParse that allows you to quickly and easily parse XML.  While this is a great plugin and does exactly as it says, I personally try not to use too many plugins in my JavaScript Programing.  So I decided to write a tutorial to show you how easy it actually is to Parse XML via jQuery.

Lets first take a look at the XML file we are going to Parse. The XML document is saved as cd_catalog.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
<?xml version="1.0" encoding="utf-8" ?>
<CATALOG>
  <CD type="physcial">
    <TITLE>Maggie May</TITLE>
    <ARTIST>Rod Stewart</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Pickwick</COMPANY>
    <PRICE>8.50</PRICE>
    <YEAR>1990</YEAR>
  </CD>
  <CD type="physical">
    <TITLE>When a man loves a woman</TITLE>
    <ARTIST>Percy Sledge</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Atlantic</COMPANY>
    <PRICE>8.70</PRICE>
    <YEAR>1987</YEAR>
  </CD>
  <CD type="digital">
    <TITLE>Big Willie style</TITLE>
    <ARTIST>Will Smith</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1997</YEAR>
  </CD>
</CATALOG>

As you see this is a simple XML document of a CD Catalog. If you have never seen an XML document before I suggest you read up on it. Now lets look at the jQuery Code we will use to extract the data. I am going to post the full code and then explain what each line does. If you don’t care what each line does then feel free to copy and paste and augment the code. Anyway here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready(function(){
  $.ajax({
    type: "GET",
    url: "cd_catalog.xml",
    dataType: "xml",
    success: function(xml){
                  $(xml).find("CD").each(function(){
                        $("#CD").append($(this).find("ARTIST").text() + "<br />");
                  });
               }
  });
});

The output of the jQuery code would look something like this:

1
2
3
Rod Stewart<br />
Percy Sledge<br />
Will Smith<br />

So now that you see the code let me explain. First you must call the $.Ajax Get Request in order to actually get the XML file. (On a side note you may also use jQuery’s $.get function to retrieve the XML document.) Click here if you don’t understand the $.Ajax Get Request. When you successfully get the cd_catalog.xml file you must call a function to process the XML. Then on Line 7 in the jQuery code

$(xml).find(”CD”).each(function() is how you actually process the XML data. First you must use the .find to search all “CD” tags in the XML document then use the .each to loop through every “CD” tag that is in the XML document. Now that we are looping through the all “CD” tags, we can output the Artist Name by using the following code on line

$(”#CD”).append($(this).find(”ARTIST”).text() + “br/”);. We must first Append data to the div with the ID CD in the HTML document. The data that we will append to the div is as follows: $(this).find(”ARTIST”).text().

What we do here is find the tag “ARTIST” within the “CD” Node and get the text within the “ARTIST” tag. As you see its pretty simple to Parse an XML document with jQuery. But there is one more topic I want to cover and that is XML tag Attributes.

In the XML document above you can see that in the “CD” tag we have an attribute called “type”. To access an attribute you can use the code below after line 7 in the above jQuery code.

1
        $(this).attr("type")

And that is it for this tutorial. We hope it will help you on your quest to become a jQuery guru.

Cheers 🙂

How “Ajax” Works!

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the “Submit” button to send/get the information, wait for the server to respond, and then a new page will load with the results.

Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

With an HTTP request, a web page can make a request to, and get a response from a web server, without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

This is a simplified introduction about how Ajax works


The user sends a request that executes an action and the action’s response is showed into a layer, identify by an ID, without reload the full page. For example a layer with this id:

<div id=”ajaxResponse”></div>

In the next steps we will see how to create an XMLHttpRequest and receive response from the server.

1. Create XMLhttpRequest

Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest.

To create this object, and deal with different browsers, we are going to use a “try and catch” statement.

function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e)
{
alert(”Your browser does not support AJAX!”);
return false;
}
}
}

2. Sending request to the server

To send off a request to the server, we use the open() method and the send() method.

The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server.

xmlHttp.open(”GET”,”time.asp”,true);
xmlHttp.send(null);

3. Writing server side script

The responseText will store the data returned from the server. Here we want to send back the current time. The code in “time.asp” looks like this:

<%
response.expires=-1
response.write(time)
%>

4. Consuming the response

Now we need to consume the response received and display it to the user.

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(”GET”,”time.asp”,true);
xmlHttp.send(null);
}

5. Complete the code

Now we must decide when the AJAX function should be executed. We will let the function run “behind the scenes” when the user types something in the username text field. The complete code looks like this:

<html>
<body>

<script type=”text/javascript”>
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e)
{
alert(”Your browser does not support AJAX!”);
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(”GET”,”time.asp”,true);
xmlHttp.send(null);
}
</script>
<form name=”myForm”>
Name: <input type=”text”
onkeyup=”ajaxFunction();” name=”username” />
Time: <input type=”text” name=”time” />
</form>
</body>
</html>

Web Applications: What are the Benefits of a Web Application?

A web application relieves the developer of the responsibility of building a client for a specific type of computer or a specific operating system. Since the client runs in a web browser, the user could be using an IBM-compatible or a Mac. They can be running Windows XP or Windows Vista. They can even be using Internet Explorer or Firefox, though some applications require a specific web browser.

Web applications commonly use a combination of server-side script (ASP, PHP, etc) and client-side script (HTML, Javascript, etc.) to develop the application. The client-side script deals with the presentation of the information while the server-side script deals with all the hard stuff like storing and retrieving the information.

How Long Have Web Applications Been Around?

Web Applications have been around since before the web gained mainstream popularity. For example, Larry Wall developed Perl, a popular server-side scripting language, in 1987. That was seven years before the Internet really started gaining popularity outside of academic and technology circles.

The first mainstream web applications were relatively simple, but the late 90’s saw a push toward more complex web applications. Nowadays, millions of Americans use a web application to file their income taxes on the web.

What is the Future of Web Applications?

Most web applications are based on the client-server architecture where the client enters information while the server stores and retrieves information. Internet mail is an example of this, with companies like Yahoo and MSN offering web-based email clients.

The new push for web applications is crossing the line into those applications that do not normally need a server to store the information. Your word processor, for example, stores documents on your computer, and doesn’t need a server.

Web applications can provide the same functionality and gain the benefit of working across multiple platforms. For example, a web application can act as a word processor, storing information and allowing you to ‘download’ the document onto your personal hard drive.

If you have seen the new Gmail or Yahoo mail clients, you have seen how sophisticated web applications have become in the past few years. Much of that sophistication is because of AJAX, which is a programming model for creating more responsive web applications.

Google Apps, Microsoft Office Live, and WebEx WebOffice are examples of the newest generation of web applications.

%d bloggers like this: