AJAX - The Complete Reference

(avery) #1

216 Part II: Applied Ajax^


The first line looks pretty familiar, but the second introduces Prototype’s infamous $()
method. In this usage, it works just like document.getElementById(), but it can do more.
Also note that the update() method is used here, which just provides an abstraction to
innerHTML.
Now, we need to bind event handlers in order to have the request be triggered by a
button request. Given markup like:

<input type="button" value="Say Hello" id="requestButton" />

Prototype’s Ruby-like Event.observe() method can be used to indicate, that the call
to sendRequest(), which should be triggered when a click event is seen.

Event.observe("requestButton", "click", sendRequest);

However, it is necessary to attach this event only after the window has loaded the
document properly.

Event.observe( window, "load", function() { Event.observe("requestButton",
"click", sendRequest);} );

The complete Prototype-specific version of “Hello World” is shown next and can be
found at http://ajaxref.com/ch5/prototypehelloworld.html.

<!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 Hello Ajax World</title>
<script type="text/javascript" src=
"http://ajaxref.com/lib/prototype/prototype.js"></script>
<script type="text/javascript">
function sendRequest()
{
new Ajax.Request("http://ajaxref.com/ch1/sayhello.php",
{
method:"GET",
onSuccess: handleResponse
});
}
function handleResponse(response)
{
var msg =
response.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
$("responseOutput").update(msg);
}

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