AJAX - The Complete Reference

(avery) #1

228 Part II: Applied Ajax^


when the load happens. The callback function will be passed responseText, status, and
a response object in its invocation. However, note that load is not part of $ and needs to be
chained to a selected object. For example, to set responseResult to some HTML response,
you would use:

$("#responseResult").load("sayHello.php");

In addition to providing shortcuts for addressing certain data specific requests, jQuery
provides a method for addressing cached requests: $.getIfModified(url,params,
callback). The idea here is that the request will be issued only if the URL has been
modified since its last retrieval. The chained load() method is updated in a similar fashion
with a corresponding conditional GET of HTML content loadIfModified(url,params,
callback). This is moderately useful to provide some local caching, but there could
certainly be much more done here.
You would likely expect to see a serialization mechanism similar to the libraries
previously discussed. Interestingly, at this point jQuery takes a different approach, relying
on an add-on library to provide this useful service. For example, you could find one form
serialization library at http://www.malsup.com/jquery/form/#download. Using such a facility,
serialization is quite simple. In this case, the ajaxForm() method of a selected item is used.

$("#ratingForm").ajaxForm();

Following, we show the core of the rating example used previously done in jQuery
style. The full example can be found at http://ajaxref.com/ch5/jqueryrating.html.

$(document).ready(function(){
$("#ratingForm").ajaxForm(function(data) {
$("#responseOutput").html(data);
});
});

The preceding code takes the form with the ID ratingForm and calls ajaxForm on it.
Now, instead of the form being submitted as normal, it will be serialized, the URL specified
in the “action” attribute will be called, and then the callback specified as the argument will
be called. If you are impressed with how much was done with so little code but are more
than a bit concerned about readability, welcome to the big trade-off of using jQuery.

The Strengths and Weaknesses of jQuery

Clearly, jQuery doesn’t add tons to the communication aspects of Ajax, so why all the
interest in the library? There are a number of reasons. In small doses, it can be quite powerful
and useful. For example, on the jQuery home page they show an example similar to this one:

$("#summary").addClass("highlight").fadeIn("slow");

In this example, the $() selector is used to find an element with the ID value of
summary. We add a class name called highlight to it and then slowly fade it into view.
Chaining these functions together when a button is pressed presents a very fast way to
perform DOM tasks that might take literally ten times the code in standard JavaScript.
However, be careful: such terseness can come with a price. Consider the serialization and
Free download pdf