AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 217


<form action="#" method="GET">
<input type="button" value="Say Hello" id="requestButton" />
</form>

<br /><br />
<div id="responseOutput"> </div>

</body>
</html>

Prototype Ajax Assistance

So far there hasn’t been much of a difference in the Ajax part of the Prototype library when
compared to the YUI offering. Prototype does indeed provide a number of useful
programmer assistance features. As you have already seen, a DOM element can be quickly
selected using the $() method. For example, $("ratingForm") would select the DOM
element with the id attribute set to ratingForm. Similar to the AjaxTCR DOM helper, it is
possible to pass this method many ID values to retrieve. As with YUI and the AjaxTCR
library, form contents can quickly be serialized. After retrieving an element that is a form,
you can call a serialize() method to collect the input to send with an Ajax request like
so: $("ratingForm").serialize(true). Even more useful is that it is possible to use a
simple Ajax pattern of inserting content returned into the page. Simply create an Ajax object
and use the Updater() method, passing it the target DOM element, URL to call, and
request options, like so:

new Ajax.Updater("responseOutput", "http://ajaxref.com/ch5/sayhello.php",
{method: "get"});

To see all of these features in action, explore the example at http://ajaxref.com/ch5/
prototyperating.html, which is listed here.

<!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>Chapter 5 : Prototype Based Ratings </title>
<script type="text/javascript" src=
"http://ajaxref.com/lib/prototype/prototype.js"></script>
<script type="text/javascript">
function sendRequest()
{
var options = {
method: "POST",
parameters: $("ratingForm").serialize(true) };
new Ajax.Updater("responseOutput",
"http://ajaxref.com/ch3/setrating.php", options);
}

Event.observe(window, "load", function() {
Event.observe("requestButton", "click", sendRequest);});
</script>
Free download pdf