wo years ago, I wrote an article for DevX comparing all of the open source AJAX frameworks that were popular at that time. If I were to write the same article today, my framework of choice would be a library that was not even on my list in 2006. In 2008, jQuery would be the framework I choose. Some informal research revealed that I’m not alone; jQuery seems to be on its way to becoming the most popular of all AJAX frameworks.
The following are the main characteristics responsible for jQuery becoming such a popular choice among developers:
- Simple programming model
- Simplicity and straightforwardness
- Basic and essential expressions/conventions requirements
To give you a sense of jQuery’s simplicity, this jQuery code sample executes an AJAX call to the backend server:
$.get( "sample.jsp", responseHandler )
As you can see, this very simple line of code is?even to users unfamiliar with jQuery?simple to understand. It contains one, appropriately named method that handles invocation of the remote service, including all of the underlying details of the cross-browser, compatible asynchronous processing (more on this later). This article provides a comprehensive introduction to this simple, yet powerful, AJAX framework.
Integration of Web Standards and Promotion of the Best Design Practices
jQuery provides native support and recognition for HTML and CSS symbols and terminology. Take a look at the syntax for changing the CSS property of a div with the ID of sampleDiv:
$("#sampleDiv").css("margin-top", "35px;");
In addition, jQuery keeps its custom code in external JavaScript files and away from the content, promoting the separation of code from content. From a design and implementation perspective, this emphasis makes jQuery a smart choice for implementing web applications in a maintainable way.
jQuery Is Well Documented and Extensible
Besides the excellent documentation available on jQuery's project web site, numerous online references and 'how to' sites are devoted to jQuery, including an original and valuable third-party web site called Visual jQuery. You will also find a number of excellent books on jQuery. One that I particularly like is jQuery in Action.
The core jQuery library also is extensible. Third-party software developers contribute jQuery plugins, many of which are extremely valuable extensions. For example, jQuery drag-n-drop is a high-quality add-on that further enhances the value of jQuery.
Installing jQuery
The jQuery JavaScript library is available for download in a "minified" (names of the variables and functions are minimized for size) compressed or uncompressed JavaScript file. Download the latest version and install it on your web page as:
Programming with jQuery
At the core of the jQuery API is a 'jQuery' object wrapper. All of the jQuery functions, effects, and manipulations of HTML and CSS content are performed through this object. It is, however, expected that you use the common '$' shortcut to invoke the jQuery functions. So, for example, instead of using the jQuery object to query the background color of the div with an ID "banner":
jQuery.("#banner").css("background-color");
You would perform the same action via the '$' shortcut:
$("#banner").css("background-color");
Loading the Document and DOM Representation
jQuery (as most other AJAX libraries) operates on a Document Object Model (DOM) representation of the page, and it needs a parsed DOM tree of the page to perform most of its functions and effects. However, a DOM model of the page is not available until the page is parsed by the browser.
A typical solution is to attach the jQuery functions that have to be available as the page loads to the window.onload event. The disadvantage of this approach is that the end user would need to wait until the page is fully loaded?including images and other external resources?before the AJAX effects get enabled. Furthermore, to truly follow the principles of unobtrusive JavaScript, XHTML content should not contain any in-markup dependencies to JavaScript.
Therefore, all of the custom JavaScript code should be kept in the external files. In the header (
section), your web page typically will have a link to the jQuery library and the link to one or more of your custom JavaScript files that may leverage jQuery.If you have jQuery events or functions to attach to the page at load time, you typically make a ready call on the document (DOM object representing a page) through jQuery and pass the custom anonymous function that may make or embed other function calls:
$(document).ready( function() { ... your function calls here ... } )
CSS and DOM Manipulation
jQuery provides excellent support for manipulating the DOM representation of HTML content and for CSS properties, qualities that make jQuery very simple and concise to program. In fact, jQuery's support for CSS properties, such as attribute-based selectors, exceeds the CSS support in most browsers. However, lack of support from browsers does not preclude jQuery from functioning properly or from accessing CSS elements in a standards-compliant fashion.
Here are some examples of how jQuery integrates DOM with organic support for CSS:
Adding a paragraph to an element with an ID sample:
$("#sample").append("Some paragraph.
");
Hiding a div:
$("div#someSection").hide();
Adding a class to a first paragraph:
$("p:first").addClass("highlighted");
Adding text to a paragraph:
$("p").html( "Some text") );
Color-interleave the odd table rows of all tables (a.k.a., "zebra" coloring):
$('tr:odd').addClass('odd');
As you can see, XHTML and CSS elements are referenced using familiar CSS and XHTML syntax?requiring no framework-specific knowledge. In addition, you can fully manipulate HTML/CSS elements referenced via jQuery, including hiding, removing, adding, and altering content, in an equally simple and intuitive fashion.
Making Asynchronous Calls
Being an AJAX framework, jQuery supports a variety of methods for making asynchronous calls to server services. In addition to other, more generic methods, jQuery supports the two most common HTTP methods for making of AJAX calls: POST and GET. The following is a GET call to a server-side resource in the simple jQuery style:
$.get("sample.asp", { itemId: "123" }, someCallbackFunction );
Notice the three parameters: URL, a parameter, and a callback to a function someCallbackFunction that will process the results from an AJAX call as a string.
jQuery supports another style of the GET method called getJSON. While making a GET call to the server, getJSON interprets the string response from the server as a JSON (JavaScript Object Notation) object and passes the results into a callback function as the JSON object, all behind the scenes.
$.getJSON("sampleJSON.asp", { itemId: "123" }, someCallbackJSONFunction );
The syntax for POST calls is almost identical. The only difference is in function name; the parameters are the same.
$.post("samplePostingResource.asp", { itemId: "123" }, somePostProcessingCallbackFunction );
In addition, jQuery provides a generic load() function for invoking server-side resources with the same syntax but with greater flexibility. It also offers a large set of additional, specialized functions for finer-grained AJAX processing (e.g., ajaxStart, ajaxSend, and ajaxSuccess).
jQuery in Action
A very simple application will demonstrate all of the interesting aspects of jQuery presented so far, specifically:
- The power and simplicity of the API
- CSS and DOM manipulation
- Asynchronous calls with direct support for JSON
The example application represents a article-aggregation site that enables users to navigate and search topic lists of interest. (Sample applications are included in the downloadable source code.) To begin, page users have access to a main page that lists articles entries related to a particular topic (in this case, Latin – see Figure 1). Entries are presented in a table with each row being a link to an article entry.
When the user clicks on an entry link, an abstract of the article displays in the area below the table (see Figure 2).
![]() Figure 1. List of Articles: A main page lists articles entries related to a particular topic, in this case, Latin. |
![]() Figure 2. Article Entry View: An abstract of the article displays in the area below the table. |
$.getJSON("http://localhost:8080/Articles/results.txt", //Gives us parsed JSON automatically { keywords: params }, //The params for the query renderTable //The callback function
The renderTable function iterates over the results (the JSON object) and presents them in a results table (see Figure 3).
![]() |
|
Figure 3. Results in the Table: The renderTable function iterates over the results (JSON object) and presents them in a results table. |
For further development, the downloadable source code includes a sample HTML file with jQuery.js and a custom article.js script file inside the Articles.war file, which also provides simplified server-side functionality. Beyond these features, jQuery also provides excellent support for event-bound operations and AJAX effects, as well as extremely structured support for third-party extensions.
jQuery's support for event-bound operations is particularly attractive for developers, as is the jQuery event-binding method. Event-bound operations are accomplished through the bind() function, which supports DOM 0, DOM 1, and DOM 2 levels in a completely transparent fashion, making this complicated aspect of cross-browsers development much simpler.
Like other AJAX libraries, jQuery also supports a number of effects typical for AJAX-enabled applications, such as slide shows, fading, animations, and others.
Worth a Look
Now you know how one mature and complete library can help you implement your AJAX/JavaScript solutions in a simple, concise, and powerful fashion. I have chosen jQuery for all of the projects I have worked on during the past twelve months, and not once has it fallen short of expectations.
I strongly recommend this library for all of your AJAX implementations, and I encourage you to further explore all of its features and its many plugins. I expect that you will find jQuery a very valuable addition.