It's no surprise that Ajax is a great way to enhance a web application. However, sometimes the code you need to write can take more time than traditional development techniques, especially when you're interacting with dynamic server-side data sets. Luckily, with the introduction of jQuery, there's now a quicker and more robust way to write JavaScript and Ajax code. The suite of Ajax functions available through jQuery makes Ajax development much easier than in the past by letting you write less code and by lending additional methods and event handlers to cover most situations.
The amount of code you need to write with jQuery is minimal, even when developing complex functions, so development is a lot faster. With these tools, Ajax is becoming a more viable option when developing a website or application—even on a tight deadline.
If you're not familiar with jQuery, it's essentially a JavaScript library that makes JavaScript development easier. It minimizes the code you need to write through its many built-in features—features for which you would typically need to write custom functions or objects. For a link to more information and to download the jQuery library, see Resources. Also, as you'll see in the sample code for this article, you can embed the current version of the jQuery library directly. This article assumes that you have an understanding of JavaScript coding.
Traditional JavaScript versus jQuery Ajax
In the past, Ajax required a lot of redundant JavaScript code to form a request and handle the response. To make a request and handle the response, you needed to:
- Determine whether to use the
XMLHTTPRequestorActiveXObjectbased on the browser - Set the callback event that would be used to receive the response
- Open the request
- Send the request
- Upon triggering the callback, check the
readyStateto determine whether the response object was ready to be accessed
Listing 1 shows the JavaScript code that would be typical when making a traditional Ajax request in the JavaScript language.
Listing 1. Traditional Ajax request
<script type="text/javascript">
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject("MSXML2.XMLHTTP");
}
request.onreadystatechange = onResponse;
request.open("GET", “url for request”, true);
request.send(null);
function checkReadyState(obj) {
if(obj.readyState == 0) { // Sending Request }
if(obj.readyState == 1) { // Loading Response }
if(obj.readyState == 2) { // Response Loaded }
if(obj.readyState == 3) { // Response Ready }
if(obj.readyState == 4) {
if(obj.status == 200) {
return true;
}
else if(obj.status == 404) {
// File not found
}
else {
// There was a problem retrieving the XML
}
}
}
function onResponse() {
if(checkReadyState(request)) {
// Handle the response with one of the following properties
//alert(request.responseXML);
//alert(request.responseText);
}
}
</script>
|
Under the surface, jQuery offers the same functions as traditional JavaScript coding, but the best part is that now you don't have to worry about writing most of it. It's not that the traditional code is difficult to write, it's that there's a lot of it and—to be frank—it can get a bit messy, especially when you see how easy it is to do it with jQuery. Listing 2 includes a simple jQuery Ajax request that's similar to the one in Listing 1.
Listing 2. Simple jQuery Ajax request
<script type="text/javascript">
$.ajax({
url: 'data/content.xml',
success: function(xml) {
// Parse the response
}
});
</script>
|
Now that's a pretty big difference. And the code could be even simpler, because
with jQuery, you don't have to rewrite all of this code every time you make a
request. A method called ajaxSetup is a great solution
that offers the ability to set default values for your Ajax requests. This is
particularly helpful when you have many requests for the same URL; if you'd like
to set a default request type, such as POST or
GET; and so on. With the jQuery library embedded, you
can easily set some defaults, like the example code in Listing 3.
Listing 3. Using ajaxSetup to set default Ajax values
<script type="text/javascript">
$.ajaxSetup({
url: 'url for request',
});
</script>
|
This example sets the default url for the request so that
any time an Ajax call is constructed, you don't need to include a
url parameter. However, if you do, it will simply override the
default setting. There are a number of parameters that you can set as defaults,
such as:
asyncbeforeSendcachecontentTypedatadataFilterdataTypeglobal
For a link to a full list with additional details, see Resources.
jQuery also offers a number of Ajax events that allow maximum control over each and every stage of the request. With them, you can modify data before the request is sent, determine whether the request was a success or failure, and monitor requests on a local or global level.
- Events triggered before a request is sent:
ajaxStart(global)beforeSend(local; allows you to modify theXMLHTTPRequestobject by setting additional headers and so on)ajaxSend(global)
- Events triggered for a successful request:
success(local)ajaxSuccess(global)
- Events triggered for an unsuccessful request:
error(local)ajaxError(global)
- Events triggered when a request is complete, regardless of success:
complete(local)ajaxComplete(global)
- Event triggered when there are no more requests being processed:
ajaxStop(global)
Requesting XML and handling the response
Now that you've seen the basic differences between traditional JavaScript and jQuery
Ajax requests, you can go a step farther by requesting a real XML file. The XML
file that you'll request—seen in Listing 4—includes
elements for a header, description,
and sourceUrl that correspond to this article and are
used to render a simple HTML page with a title, description, and hyperlink to the
downloadable source code.
Listing 4. XML example for Ajax request with jQuery
<?xml version="1.0" encoding="UTF-8"?>
<content>
<header>Improving Ajax Development with jQuery</header>
<description>It's no surprise that Ajax is a great way to enhance a web
application. However, sometimes the code that needs to be written can take more
time than traditional development techniques, especially when you're interacting
with dynamic server-side data sets. Luckily, with the introduction of jQuery there's
now a quicker and more robust way to write JavaScript and Ajax. The suite of Ajax
functionality available through jQuery makes Ajax development much easier than the
past by allowing you to write less code and by lending additional methods and event
handlers to cover any situation. The amount of code that needs to be written with
jQuery is very minimal, even when developing complex functionality, so development
is a lot faster. With these tools Ajax is becoming a more viable option when
developing a website or application, even on a tight deadline.</description>
<sourceUrl>
http://articles.studiosedition.com/ibm/improving_ajax/ImprovingAjaxDevWithJQuery.zip
</sourceUrl>
</content>
|
The first thing you need to do to request and parse this XML is embed the jQuery
library. Ideally, you would include a separate JavaScript file for your custom code;
but for the purpose of this article, the HTML example includes the JavaScript code.
To ensure that all the page elements are fully loaded and available to the
JavaScript language, you make an Ajax request when the page is finished loading.
jQuery has a simple event called ready that you can
use for this function: Apply it to the document object. When the
ready event is triggered, the corresponding function
is called, and you can proceed with your Ajax request. All of the examples in this
article use this process to ensure that everything is accessible within the page.
When the page is ready, you can form your Ajax request using jQuery. As you can see in Listing 5, the request is similar to the one you've already seen, but now you're handling success and error responses.
Listing 5. Requesting and parsing XML with Ajax and jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Improving Ajax Development with jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'data/content.xml',
success: function(xml) {
var header = description = sourceUrl = '';
var content = xml.getElementsByTagName('content');
for(var i=0; i<content.length; i++) {
for(var j=0; j<content[i].childNodes.length; j++) {
switch(content[i].childNodes[j].nodeName) {
case 'header':
header = content[i].childNodes[j].firstChild.data;
break;
case 'description':
description = content[i].childNodes[j].firstChild.data;
break;
case 'sourceUrl':
sourceUrl = content[i].childNodes[j].firstChild.data;
break;
default:
//
}
}
}
$("body").append('<h1>'+header+'</h1>');
$("body").append('<p>'+description+'</p>');
$("body").append('<a href="'+sourceUrl+'">Download the source</a>');
},
error: function(xhr, status, err) {
// Handle errors
}
});
});
</script>
</head>
<body>
</body>
</html>
|
The success event receives three arguments:
data, textStatus, and
XMLHttpRequest. The data
parameter is the only parameter this article uses: The example names this parameter
xml, so that it's easy to identify that this is XML data
being returned as the response. Looking back at the XML file, you know that you
can expect a header, a description,
and a sourceUrl, so iterate through the children in the
file and assign these values to associated variables. When all the variables have
values, you can render the data as HTML by appending each one to the body of the
HTML page and applying basic formatting. If the request failed, the
error event would have been triggered, which would
have presented three arguments: XMLHttpRequest,
textStatus, and errorThrown.
The XMLHttpRequest parameter would have been the
actual object; the textStatus is a string that describes
the type of error that occurred; and the errorThrown
parameter is an optional exception object.
Requesting JSON and handling the response
With JSON, the process is similar to requesting XML: The main differences are setting
the dataType parameter to the appropriate value,
parsing the data, and adding a shorthand method that can be used as an alternative
to the typical jQuery Ajax request. This section covers all of these differences.
The code in Listing 6 is a sample JSON file that includes the same data as the XML file in Listing 4. The goal is to render the same HTML file using this data. One important thing to remember is to make sure your JSON is strict, as any malformed JSON is rejected and a parse error will be thrown.
Listing 6. JSON code for a sample request
{"content":
{
"header": "Improving Ajax Development with jQuery",
"description": "It's no surprise that Ajax is a great way to enhance a web
application. However, sometimes the code that needs to be written can take more
time than traditional development techniques, especially when you're interacting
with dynamic server-side data sets. Luckily, with the introduction of jQuery there's
now a quicker and more robust way to write JavaScript and Ajax. The suite of Ajax
functions available through jQuery makes Ajax development much easier than the
past by allowing you to write less code and by lending additional methods and event
handlers to cover any situation. The amount of code that needs to be written with
jQuery is very minimal, even when developing complex functions, so development
is a lot faster. With these tools Ajax is becoming a more viable option when
developing a website or application, even on a tight deadline.",
"sourceUrl":
"http://articles.studiosedition.com/ibm/improving_ajax/ImprovingAjaxDevWithJQuery.zip"
}
}
|
To form the request and parse the JSON response, you must set up your HTML
to be similar to the XML example by first embedding the jQuery library, and then
including your custom code in a ready event. In
Listing 7, you'll see that there is a new dataType
parameter in the Ajax request: You use this parameter to inform jQuery that
you are expecting a JSON response, so that a JavaScript object is returned
for you to easily parse. Behind the scenes, jQuery is using the
parseJSON function, which takes a well-formed
JSON string and returns the resulting JavaScript object. This means that jQuery
requests the JSON data, converts it to a JavaScript object, and returns the
JavaScript object as a response so that you don't have to do anything but
access the object. This process saves you from writing custom functions and
additional code.
Listing 7. Requesting and parsing JSON with Ajax using jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Improving Ajax Development with jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'data/content.js',
dataType: 'json',
success: function(js) {
$("body").append('<h1>'+ js.content.header+'</h1>');
$("body").append('<p>'+ js.content.description+'</p>');
$("body").append('<a href="'+ js.content.sourceUrl+'">Download the source</a>');
},
error: function(xhr, status, err) {
// Handle errors
}
});
});
</script>
</head>
<body>
</body>
</html>
|
Parsing JSON after it has been converted to a JavaScript object is just like accessing
any JavaScript object's properties and functions with dot notation. In
Listing 8, you'll see that the data
parameter for the success event is named
js: This is so you can easily identify that it is
your JavaScript object. The js object takes on the
structure of the JSON file, so you can access the content
object, and then the header, description,
and sourceUrl within the content
object. The HTML is rendered similarly to the XML example by applying simple
mark-up and appending it to the <body> element
of your HTML page.
Alternatively, you can use another shorthand method for requesting JSON called
getJSON, which loads JSON data from a server using
the GET method. You can see the equivalent of the
previous request you made for JSON using the getJSON
method in Listing 8.
Listing 8. Requesting and parsing JSON data with getJSON
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('data/content.js', function(js) {
$("body").append('<h1>'+ js.content.header+'</h1>');
$("body").append('<p>'+ js.content.description+'</p>');
$("body").append('<a href="'+ js.content.sourceUrl+'">Download the source</a>');
});
});
</script>
|
Requesting HTML and handling the response
The final static data set that you request is HTML. The HTML in Listing 9 is what you have been producing in the previous examples.
Listing 9. HTML example for an Ajax request with jQuery
<h1>Improving Ajax Development with jQuery</h1>
<p>It's no surprise that Ajax is a great way to enhance a web application.
However, sometimes the code that needs to be written can take more time than traditional
development techniques, especially when you're interacting with dynamic server-side data
sets. Luckily, with the introduction of jQuery there's now a quicker and more robust way
to write JavaScript and Ajax. The suite of Ajax functions available through jQuery
makes Ajax development much easier than the past by allowing you to write less code and
by lending additional methods and event handlers to cover any situation. The amount of
code that needs to be written with jQuery is very minimal, even when developing complex
functions, so development is a lot faster. With these tools Ajax is becoming a more
viable option when developing a website or application, even on a tight deadline.</p>
<a href="http://articles.studiosedition.com/ibm/
improving_ajax/ImprovingAjaxDevWithJQuery.zip">
Download the source
</a>
|
HTML is probably the easiest response type to handle because there's nothing to parse.
To set up a request for HTML, you start like the previous examples—by
embedding the jQuery library, and then adding your custom JavaScript code within
the ready event. As you did with the JSON
example, the code in Listing 10 also uses the
dataType parameter, and you set its value to
html, which tells jQuery to return the HTML as plain
text rather than XML or a JavaScript object, as in the previous examples. The
function is similar to traditional JavaScript Ajax requests when using the
responseText property, which returns plain text.
Another nice feature is that if script tags are present in the HTML result set,
they are evaluated when added to the HTML page, so you can have additional
JavaScript code that is executed after the HTML data is added to the page.
As before, the success and error
events are applied, and the data parameter is named
according to the actual data type—in this case, html—so
you can easily identify it. Because the HTML data does not need to be parsed,
you can simple append it to the body of the HTML page and you're done.
Listing 10. Requesting and parsing HTML with Ajax using jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Improving Ajax Development with jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'data/content.html',
dataType: 'html',
success: function(html, status, xhr) {
$("body").append(html);
},
error: function(xhr, status, err) {
// Handle errors
}
});
});
</script>
</head>
<body>
</body>
</html>
|
With multiple static data types under your belt, it's time to discuss working with dynamic data. You'll be using PHP as your server-side language, which generates the response, but you could use any server-side language you prefer to create this kind of process. Typically, you would use this process to retrieve data from a database based on certain parameters, such as a user ID. In this case, you simply return an XML data set like the one used in the Requesting XML and handling the response section, but PHP requires a certain parameter to return the data.
The PHP code in Listing 11 is what you'll request using Ajax. It begins
by setting the content type of the data it will be returning to XML with a UTF-8
charset. Then, before it returns the XML data, it requires a parameter through
POST named secret and
requires that its value be equal to ajax. If these
requirements are not met, PHP returns no data. Therefore, when you create your
request, you need to ensure that you POST a
secret with a value of ajax
to retrieve the XML data set.
Listing 11. PHP example that Ajax will request
<?php
header("Content-Type: application/xml; charset=UTF-8");
if(isset($_POST['secret']) && $_POST['secret'] == 'ajax')
{
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<content>
<header>Improving Ajax Development with jQuery</header>
<description>It's no surprise that Ajax is a great way to enhance a web
application. However, sometimes the code that needs to be written can take more
time than traditional development techniques, especially when you're interacting
with dynamic server-side data sets. Luckily, with the introduction of jQuery there's
now a quicker and more robust way to write JavaScript and Ajax. The suite of Ajax
functions available through jQuery makes Ajax development much easier than the
past by allowing you to write less code and by lending additional methods and event
handlers to cover any situation. The amount of code that needs to be written with
jQuery is very minimal, even when developing complex functions, so development
is a lot faster. With these tools Ajax is becoming a more viable option when
developing a website or application, even on a tight deadline.</description>
<sourceUrl>
http://articles.studiosedition.com/ibm/improving_ajax/ImprovingAjaxDevWithJQuery.zip
</sourceUrl>
</content>";
}
?>
|
The code in Listing 12 is similar to the original XML example,
with the exception of the url, type,
and data parameters. As always, you start by embedding
the jQuery library, then you include your custom JavaScript code within a
ready event. Now for the differences: Notice that
the url parameter's value has changed. This time,
you're requesting a PHP file that will contain the code you just covered. Next
is a type parameter, which is set to
POST so that the PHP file will receive the data you
send to it using the correct HTTP method. Then, you set the data
parameter to secret=ajax, which is in the format of a
query string and will be accessible through PHP's $_POST
function.
Listing 12. Requesting and parsing dynamic data with Ajax using jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Improving Ajax Development with jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'data/content.php',
type: 'POST',
data: 'secret=ajax',
success: function(xml) {
var header = description = sourceUrl = '';
var content = xml.getElementsByTagName('content');
for(var i=0; i<content.length; i++) {
for(var j=0; j<content[i].childNodes.length; j++) {
switch(content[i].childNodes[j].nodeName) {
case 'header':
header = content[i].childNodes[j].firstChild.data;
break;
case 'description':
description = content[i].childNodes[j].firstChild.data;
break;
case 'sourceUrl':
sourceUrl = content[i].childNodes[j].firstChild.data;
break;
default:
//
}
}
}
$("body").append('<h1>'+header+'</h1>');
$("body").append('<p>'+description+'</p>');
$("body").append('<a href="'+sourceUrl+'">Download the source</a>');
},
error: function(xhr, status, err) {
// Handle errors
}
});
});
</script>
</head>
<body>
</body>
</html>
|
As you can see, jQuery's data parameter offers great possibilities.
This code example shows how easy it is to communicate between jQuery and a
server-side programming language in addition to exchanging variables and their
values. The possibilities are truly limitless, and with jQuery, it just got easier.
Now that you've seen all of the basic Ajax techniques using jQuery, it's easy to see that the jQuery library improves Ajax development by making it much easier, requiring less code and providing additional control. These enhancements provide the foundation for rapidly building complex Ajax-enabled applications without writing a lot of code or needing broader deadlines. This article's samples alone prove how quick and easy it is build complex Ajax interactions in no time at all using jQuery—even when using multiple programming languages.
| Description | Name | Size | Download method |
|---|---|---|---|
| Sample Ajax scripts used in this article | ImprovingAjaxDevWithJQuery.zip | 12KB | HTTP |
Information about download methods
Learn
-
Learn more about jQuery's philosophy, features, and functions in
"Simplify
Ajax development with jQuery" (developerWorks, April 2007).
-
Learn more about Ajax programming in the Ajax
resource center.
-
Find more information about the jQuery library at the
jQuery site.
-
View a full listing of the parameters
that you can set to default values using
ajaxSetup. - The
Web development zone specializes in articles covering various
web-based solutions.
-
IBM
technical events and webcasts: Stay current with developerWorks' technical
events and webcasts.
-
developerWorks on-demand
demos: Watch demos ranging from product installation and setup for beginners
to advanced functions for experienced developers.
Get products and technologies
-
Directly embed the current version of the jQuery library from
Google.
-
Download IBM product evaluation
versions or explore
the online trials in the IBM SOA Sandbox and get your hands on application
development tools and middleware products from DB2®, Lotus®, Rational®,
Tivoli®, and WebSphere®.
Discuss
- Create your My developerWorks profile today and setup a watchlist on Ajax or jQuery.
Get connected and stay connected with My developerWorks.
- Find other developerWorks members interested in web development.
- Web developers, share your experience and knowledge in the web development group.
- Share what you know: Join one of our developerWorks groups focused on web topics.
- Roland Barcia talks about Web 2.0 and middleware in his blog.
- Follow developerWorks' members' shared bookmarks on web topics.
- Get answers quickly: Visit the Web 2.0 Apps forum.
- Get answers quickly: Visit the Ajax forum.

Kris Hadlock has been a contract web developer and designer since 1996. He has worked on projects for companies such as SPIN Magazine, IKEA, United Airlines, JP Morgan Chase, GoDaddy Software, and Fire Mountain Gems. He is the author of Ajax for Web Application Developers (Sams) and The ActionScript Migration Guide (New Riders) as well as a featured columnist and writer for numerous websites and design magazines, including Peachpit.com, InformIT.com, and Practical Web Design magazine. Kris is also the founder of www.studiosedition.com, a web design and software development studio specializing in fusion of form and function.




