JQuery and XML: Using JQuery and Ajax to Process and Read an XML File
JQuery is the most popular JavaScript library in use today. According to the statistics, more than 80% of the top 10, 000 most-visited websites in the world use JQuery in some form or the other. JQuery is not a language in itself, but it’s a part of JavaScript. JQuery makes it easy to develop interactive webpages and applications. It greatly extends the capabilities o JavaScript. With JQuery, you can navigate document, manipulate DOM elements in the document, introduce events, develop animations and create applications (using Ajax). This course shows you how web programming can be made easy with JQuery and Ajax.
JQuery is often used in conjunction with Ajax and XML. Ajax lets you create web applications that are able to operate asynchronously. This means that they don’t interfere with the current browser page when they process, send and receive information. They can work completely in the background. XML (Extensible Markup Language), on the other hand, is a language similar to HTML, but with a markedly different function. While the purpose of HTML is to display data, XML just stores data and transports it when necessary.
In this tutorial, we’re going to take a look at how you can use JQuery and Ajax code to process and read an XML file. You need to have a basic understanding of JQuery, Ajax and XML. If you’re unfamiliar with any one (or all three), we recommend that you go through this course that teaches you web development from scratch – with JQuery, Ajax and XML.
Creating an XML File
First, we need to create a simple XML file that we can read with JQuery. You can use any XML file with JQuery, provided that it’s less than 5MB in size. If it’s bigger than that, it may cause your system to slow down, or even hang. It’s possible to read larger XML files of course. There are several plugins out there made especially for this purpose. XML files can also be turned into JSON objects before they are read. You can learn more about XML programming with this course.
We’ll write an XML file that contains the names, and brief descriptions, of three cars:
//Code to create XML file <?xml version="1.0" encoding="utf-8" ?> //name the list of cars (url) <cars> //Create three cars <car> <Title> Spyder </Title> <Manufacturer> Ferrari </Manufacturer> </car> <car> <Title> M3 </Title> <Manufacturer> BMW </Manufacturer> </car> <car> <Title> Gallardo </Title> <Manufacturer> Lamborghini </Manufacturer> </car> </cars>
We’ve created a simple XML file that contains three cars and the names of their manufacturers. XML, as we mentioned earlier, can just store and transport data. XML, and by extension XML files, cannot do anything else, which is why we need to use JQuery and Ajax to read the data contained in the XML file. If there are errors in your XML file (if you get the syntax wrong), JQuery won’t work.
JQuery Code
Now, we need to read the XML file using JQuery. The first thing you should do is to include JQuery in your program:
<script src="jquery.min.js" type="text/javascript"></script>
We will be using the document ready function in JQuery that is used to prepare and read the XML document. To learn more about writing your own JQuery program, check out this course. The syntax of the document ready function is as follows:
$(document).ready(function(){ });
The body of the document ready function will include the Ajax code that will read the XML file. There are 4 parameters you have to specify: the url, dataType, success and type. The success function (xml) will hold the remaining code. The syntax is:
$.ajax({ type: "GET", url: "cars.xml", dataType: "xml", success: function(xml) { //remainder of the code } });
The HTTP request get will process the XML file. The url was the name of the list of cars, while the dataType is xml. In the success parameter, we’ve defined a function that executes when the file is successfully processed. The function (in out case) will loop through the XML code and read the file. We can also write code to print out an output, if necessary. We can also write a separate function that prints out an error message if the XML file didn’t get processed correctly (due to an error in the syntax):
error: function() { alert("The XML File could not be processed correctly."); }
This function will follow the success parameter, as shown below:
$.ajax({ type: "GET", url: "cars.xml", dataType: "xml", success: function(xml) { } //other code error: function() { alert("The XML File could not be processed correctly."); } });
To learn more about Ajax development and HTTP requests, check out this course.
Finally, we come to the final part of the program. Now that we have fetched the data in the XML file, what do we do with it? We can read the data and display it to the user. To do that, we need to use the find method to first collect data that matches our input (the list of cars, for example). Then, we need to loop through the data that’s collected and print it out. That can be done using the each function. The syntax for the find method and the each function is as follows:
$(xml).find('car').each(function(){ });
In out case, the code within the function will be this:
$(xml).find('car').each(function(){ var Titles = $(this).find('Title').text(); var Manufacturers = $(this).find('Manufacturer').text(); $("<li></li>").html(Titles + ", " + Manufacturers).appendTo("#Autom ul"); });
Here, we’re finding and fetching the data that is stored under the name “cars”. This will retrieve all three cars that were stored in the XML file. We’ve appended the node value from ‘Manufacturer’ and ‘Title’ in the final line of the code to a new variable we’ve created called “Autom”. This variable has to be declared in the body of the document ready function.
The Entire Program
Your entire program should look something like this:
$(document).ready(function(){ //the variable to be appended here $("#Autom").append("<ul></ul>"); }); $.ajax({ type: "GET", url: "cars.xml", dataType: "xml", success: function(xml) { } $(xml).find('car').each(function(){ var Titles = $(this).find('Title').text(); var Manufacturers = $(this).find('Manufacturer').text(); $("<li></li>").html(Titles + "-" + Manufacturers).appendTo("#Autom ul"); }); error: function() { alert("The XML File could not be processed correctly."); } }); Output: Spyder Ferrari M3 BMW Gallardo Lamborghini
You will receive the error output if there was a mistake in the XML file.
Note that you can change the final line of code to print the names of the manufacturer first and the names of the cars second:
$("<li></li>").html(Manufacturers + "-" + Titles).appendTo("#Autom ul"); Output: Ferrari Spyder BMW M3 Lamborghini Gallardo
As you can see, the JQuery code required to read an XML file can be pretty complicated. The bigger the XML file is, the harder the code gets. In most cases, it’s easier to use a JQuery plugin to read (and parse) XML files.
To understand the example given here better, we recommend that you type it out and execute it in your browser. There may be some compatibility issues if you are running the code in IE, but you should be fine if you’re using other browsers. If you’re having trouble understanding the terminology used here, or any part of the code in general, you can take a look at our tutorials for help. Alternatively, you can sign up for our comprehensive web development course that shows you how JQuery, Ajax and XML all come together in one project!
Recommended Articles
Featured course
Last Updated August 2024
JavaScript projects explore JavaScript to connect to APIs retrieve JSON data with AJAX use it within your web page | By Laurence Svekis
Explore CourseAjax (programming) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.