A good AJAX library lets the same Web application code work whether or not the user is allowing your page to use JavaScript.
In the midst of the often amorphous constellation of ideas and efforts known as Web 2.0, there are refreshingly concrete examples of great technologies being created and used by enthusiastic developers. John Resig’s jQuery is an excellent example.
JQuery is a JavaScript library that makes writing JavaScript, including sophisticated Web 2.0 effects and Asynchronous JavaScript and XML (AJAX) behavior easier, faster and cleaner. JQuery’s motto is “Writing JavaScript code should be fun.”
Beginners may wonder why one would use a JavaScript library. Rather than writing all your JavaScript functionality from scratch — often times “reinventing the wheel” — you can leverage the power of a library for common tasks, leaving you free to concentrate on the unique, creative portions of your project. JQuery is a particularly well-written and clever library, and it also happens to be tiny — the uncompressed version is a mere 15KB.
Two notable strengths of the jQuery project are: 1) the momentum of the community working on the project and contributing extensions and 2) the importance placed on documentation. The project Web site has plenty of documentation to help you understand and use jQuery, as well as a number of handy tutorials that help new folks get up and running.
From the jQuery Web site, you can can download the latest version of the library, get plugins and extensions, and access the documentation.
Let’s explore a simple, hands-on example. To complete this exercise, you need only a Web browser with JavaScript enabled and your favorite text editor. The example is fairly generic so you can adapt it to your specific needs. Because AJAX is so useful, we’ll try out jQuery’s AJAX module.
AJAX enables you to create Web pages that asynchronously exchange small chunks of information with a back-end server, thus avoiding full page loads. For example, if you want to change one specific part of the page based on the action of the user — say, recalculating the total in a shopping cart when the user adjusts a quantity — rather than forcing the user to wait for a new version of the entire page to load, you can simply update the portion that needs updating, leaving the user free to continue using the page uninterrupted.
There are two major components to our example: a Web page that uses jQuery to perform an AJAX request and render the results, and a server-side script that answers the request for data.
For the purposes of keeping this example down to a manageable size, we simply use canned HTML rather than build a true database-querying script. However, in the real world, your script will query a database via a server-side script based on the parameters passed in by the AJAX query.
The steps we take are as follows:
1. Create a simple Web page and a simple, external CSS stylesheet.
2. Write the AJAX query using jQuery.
3. Install our canned server response.
4. Test.
In our hypothetical situation, the Web page is the front end for a discussion forum. When the user selects the discussion thread, we update the page with the contents of that thread.
Begin by obtaining the latest version of jquery.js and saving it in a new directory.
In the same directory, create a new file called index.html containing the following text:
/p>
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
$(function() {
$(“a[@rel]”).click(function() {
$(“#container”).load(this.href, {thread_count: this.rel});
return false;
});
});
LinuxWorld jQuery Example
This example demonstrates requesting data from a back-end server via AJAX using jQuery. When the link below is clicked, the load function queries the database (in this case simply a local file), and the results of the query are rendered below the link. Note that, because we are using AJAX, there is no page load. See “AJAX Applications with jQuery” for more information.
Discuss This Article
We haven’t installed the rest of our components, so index.html doesn’t actually do anything interesting yet, but before we continue, let’s take a moment to understand what’s happening. Most of the file is ordinary HTML you might encounter in any average page. I assume you do not need the simple stuff explained, and I will concentrate on the jQuery-specific lines.
The following line tells the browser to use jquery:
The lines between the next set of
The first argument to load() is the URL of the external source, and the second argument contains parameters sent as key/value pairs to the server. As you will see, this.rel is the rel of the clicked “a” tag. We use this.rel to retrieve the proper number of posts for each article on the page. Pass this information to the back-end server as the sole parameter to load() and name it thread_count:
$(“#container”).load(this.href, {thread_count: this.rel});
Observant readers will notice that, rather than use the actual URL as the first argument to load(), we use this.href. This enables us to use the real URL as the href in the “a” tag. That is useful for degradation/fallback. If the user’s browser is not JavaScript compatible, or if the user has disabled JavaScript, then the hyperlink created by the “a” tag will still work — just not as elegantly as it does when JavaScript is enabled. With JavaScript enabled, the result of the query will be inserted in the container div without requiring a page load.
In this example, we use a local file called “cached_server_response”. To use this example with a server-side script in, for instance, Perl, PHP or Ruby, replace the url in the href with the URL of your script. Note that the host of the script and the host of this index.html file must be in the same DNS domain.
We could pass the article_id to load(), but instead we append it to the end of the href URL, again to support proper fallback behavior:
Of course, since we’re using a local file, the name/value pair does nothing and is simply ignored by the browser, but I’ve included it so you can see how it would be constructed when accessing a server script.
One last note about degradation: Because we want the “a” link to work whether or not the browser is JavaScript-enabled, it’s important to have our back-end script return HTML, as opposed to XML or JavaScript Object Notation.
The function ends with “return false;”, and that prevents the normal hyperlink behavior from executing when the user clicks the a link.
The content between the
tags is run-of-the-mill HTML. However, look closely at the “a” tag and the div immediately following. As discussed above, the href is the URL of our data source — in this case a plain file called “cached_server_response.” The rel is 5, thus allowing us to pass along the desired number of posts in the load().Finally, the div has an id “container”, and that allows us to load our data into the proper position within the DOM and therefore display it in the proper place, properly styled, on the Web page:
Whew! That’s quite a bit of information to digest. Take a moment to review the code to understand how it works.
Now create a new file called cached_server_response containing the following sample text:
I beg to differ. Vivamus mollis,metus quis malesuada congue, sapien
urna viverra orci, sit amet vehiculadiam odio sit amet est. Aliquam
elementum aliquam nulla
You probably noticed that we reference an external CSS stylesheet in index.html. Let’s create that now. Still in the same directory, create a file called sample.css containing the following text:
html {
font-family: Verdana, Helvetica, sans-serif;
font-size: 14px;
color: #555;
background: #fff;
}
div#outerbox {
width: 612px;
margin-left: auto;
margin-right: auto;
border: 1px solid #afafaf;
background: #efefef;
padding: 20px 20px 20px 20px;
}
.comment {
padding: 6px;
border: 1px solid #afafaf;
background: #fff;
margin-top: 4px;
}
You should now have four files in your directory: index.html, jquery.js, cached_server_data, and sample.css, and it’s time to test! Open index.html in your JavaScript-enabled browser. You should see a simple block of text, styled.
Click the “Discuss This Article” link, and the posts from our cached_server_response file should appear below the link without loading a new version of the page.
This example is intentionally simplistic. In production, you will want to include additional functionality, and you may choose to use some contemporary Web effects. Fortunately, jQuery provides the wherewithal to get the job done.
To learn more about jQuery, visit the site, read the documentation, and try the tutorials. Also be sure to visit Yehuda Katz’s excellent Visual jQuery site, where you will find a tremendously useful jQuery reference as well as Visual jQuery Magazine.
If you’d like to stay current with developments in the jQuery world, read the jQuery blog or join the jQuery mailing list, both available from the main jQuery site.





I agree. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam tellus elit, accumsan at, tristique ac, congue ut, eros. Nunc
eleifend massa imperdietdiam. Integer est. Fusce non neque.