Friday, January 09, 2009

AJAX And jQuery

AJAX (Asynchronous JavaScript and XML) has become a powerful platform for building web applications with extensive client-side interactivity. Unlike older approaches, which require reloading of the entire page with every postback, AJAX uses the JavaScript DOM, the XMLHttpRequest object, XML, and CSS to download and display just the content that needs to change. ASP.NET AJAX library, part of ASP.NET 3.5, wraps up the related AJAX features into a set of JavaScript functions so that developers can easily do tasks like partially page update.

ASP.NET AJAX is great, but more and more ASP.NET AJAX developers move to jQuery. Comparing to ASP.NET AJAX, jQuery is more flexible, efficient and platform independent.

What’s jQuery anyway? jQuery is a lightweight yet powerful JavaScript library that simplifies various task for developers like HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

jQuery is written by JavaScript and all old JavaScripts are still working fine on jQuery framework. jQuery provides its standard jQuery object under the dollar symbol $. jQuery uses CSS style selectors which makes manipulations on page DOM objects very easy. Following example shows how to dynamically filter images based on the photo’s categories:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ddlCategory").change(ddlCategoryChanged);
});
function ddlCategoryChanged() {
var categoryID = $("#ddlCategory :selected").val();
$(".photo").find("li").each(function(i) {
var ids = $(this).find("input:hidden").val();
$(this).show();
if (categoryID != "0" && !hasIDInlist(ids, categoryID)){
$(this).hide();
}
});
}
function hasIDInlist(ids, selectedID) {
if (ids) {
var idSplit = ids.split(',');
for (i = 0; i < idSplit.length; i++) {
if (idSplit[i] == selectedID) {
return true;
}
}
}
return false;
}
</script>
</head>
<body>
Filter photos by category:
<select name="ddlCategory" id="ddlCategory">
<option value="0">All</option>
<option value="1">Outdoor</option>
<option value="2">Indoor</option>
<option value="3">Family</option>
<option value="4">Friends</option>
<option value="5">Colleagues</option>
</select>
<ul class="photo">
<li><img src='photo1.gif' /><br />Photo 1
<input type="hidden" value='1,5'/></li>
<li><img src='photo2.gif' /><br />Photo 2
<input type="hidden" value='2,3'/></li>
<li><img src='photo3.gif' /><br />Photo 3
<input type="hidden" value='1,4'/></li>
<li><img src='photo4.gif' /><br />Photo 4
<input type="hidden" value='1,3'/></li>
<li><img src='photo5.gif' /><br />Photo 5
<input type="hidden" value='2,3'/></li>
<li><img src='photo6.gif' /><br />Photo 6
<input type="hidden" value='5'/></li>
<li><img src='photo7.gif' /><br />Photo 7
<input type="hidden" value='4'/></li>
<li><img src='photo8.gif' /><br />Photo 8
<input type="hidden" value='1,4'/></li>
</ul>
</body>
</html>
Each photo’s category Ids are stored in a hidden field. Instead of putting event handler inside each control like onclick=’javascriptFunction’, the selection dropdown event handler is registered in an unobtrusive way ($("#ddlCategory").change(ddlCategoryChanged);) When event is fired, it will go through all photo containers by selecting <li> HTML element under CSS class of photo; the category Ids are retrieved and are compared with the selected category ID; the photo container’s visibility is set based on the category ID comparison result. All these are accomplished by just a few lines of jQuery code:
    $(".photo").find("li").each(function(i) {
var ids = $(this).find("input:hidden").val();
$(this).show();
if (categoryID != "0" && !hasIDInlist(ids, categoryID)){
$(this).hide();
}});
jQuery has great AJAX support, and the AJAX invocation in jQurey is super concise (could be only one line of code). jQuery version 1.3.2 offers six AJAX function calls:

jQuery.ajax(options): Load a remote page using an HTTP request; the most customizable AJAX function in jQuery.
jQuery.load(url, data, callback): Load HTML from a remote file and inject it into the DOM.
jQuery.get(url, data, callback, type): Load a remote page using an HTTP GET request.
jQuery.getJSON( url, data, callback ): Load JSON data using an HTTP GET request; supports Cross-Domain call.
jQuery.getScript( url, callback ): Loads, and executes, a local JavaScript file using an HTTP GET request.

It's quite simple to use those jQuery AJAX functions. Following example shows how to get current time from a jQuery call. Suppose we have a simple page to display current time (Time.aspx):
<%@ page language="C#" %>
<html>
<head>
<title>Simply show current time</title>
<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
</script>
</head>
<body>
<asp:Label ID="lblTime" runat="server"></asp:Label>
</body>
</html>
Then we can get current time from another page using jQuery ajax call:
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnGetTime").click(btnClick);
});
function btnClick() {
var searchUrl =
"Time.aspx";
$.ajax({
url: searchUrl,
success: function(data) {
//alert($(data).filter(
"#lblTime").html());
$(
"#divResult").html(data);
}
});
}
</script>
</head>
<body>
<input type="button" value="Get Current Time" id="btnGetTime">
<div id="divResult">
</div>
</body>
</html>
The clean html is another advantage of using jQuery. No postback, no view states are required or generated by jQuery when we use jQuery inside ASP.NET.