Welcome to the Understand jQuery Ajax function article series. In previous articles, we explained what a jQuery Ajax function is and how to consume various methods using a jQuery Ajax function. Please have a look at the following link.
In this article, we will learn how to read an XML file using a jQuery Ajax method with suitable examples. Before starting this article we must understand the request type of the jQuery Ajax function. There are two popular request types over HTTP, they are GET and POST (let's neglect the others for the time being, we will dedicate one entire article to understanding them). Now, when we attempt to get a value from the server we must use a GET method (like clicking one link) and when some data is posted to the server we must use a POST method (like form submission). So, here we are attempting to get a value from XML data, in other words, we must use a GET method. OK, let's try to implement it.
Step 1. Create an XML file to read
In this step, we will create one simple XML file that we will read using a jQuery Ajax function. Here is a sample code for the XML file.
<?xml version="1.0" encoding="utf-8" ?>
<BookList>
<Book>
<Title>Learn AJAX</Title>
<Publisher>Perason</Publisher>
</Book>
<Book>
<Title>Learning jQuery</Title>
<Publisher>PACKT</Publisher>
</Book>
<Book>
<Title>Head First jQuery</Title>
<Publisher>O'Reilly</Publisher>
</Book>
<Book>
<Title>jQuery UI 1.8</Title>
<Publisher>PACKT</Publisher>
</Book>
</BookList>
This is a very simple book.xml file containing a set of authors and publishers.
Step 2. Write jQuery Ajax function to get data
We will now develop a jQuery Ajax function to read the data. First, give the reference for the jQuery plugin. In this example, we are using jQuery version 1.7.1.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script src="jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "book.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('Book').each(function () {
var sTitle = $(this).find('Title').text();
var sPublisher = $(this).find('Publisher').text();
$("#content").append('<li>' + sTitle + ", " + sPublisher + '</li>');
});
}
});
});
});
</script>
</head>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>
</body>
</html>
If we look closely at the Ajax function then we will find that we have specified the type as GET, in other words, we are reading data from the XML file. Within the success function, we are reading data depending on the XML structure. Here is a sample output.
Conclusion
In this small article, we have learned how to read XML data using a jQuery Ajax method.
Hope you have understood the concept. Have a nice day.