AJAX - The Complete Reference

(avery) #1

226 Part II: Applied Ajax^


You could then go and shove this into the <div> called responseOutput. Normally, the
innerHTML property could be used, but jQuery provides an html() method to do the same
thing and chain with the selector like so:

var msg = $(responseXML,message").text();
$("#responseOutput").html(msg);

Of course, to get terse, you might use something more like this:

$("#responseOutput").html($(responseXML, "message").text());

To finally complete the hello world example, you simply need to set up a trigger to send
off a request. The jQuery library provides a similar set of chaining for binding functions to
particular events. For example, here a small function is bound to invoke sendRequest()
when the button is clicked:

$("#requestButton").click(function(){sendRequest();});

Given the need to execute code after the DOM has loaded, jQuery provides a ready()
function that could be run on the document that acts similar to adding functions to
window.onload. Here the Ajax communication trigger is bound only when the document
is ready:

$(document).ready(function(){
$("#requestButton").click(function(){sendRequest();});
});

With all the basics out of the way, we present a complete jQuery hello world example as
shown here and found at http://ajaxref.com/ch5/jqueryhelloworld.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 - jQuery Hello Ajax World</title>
<script type="text/javascript" src=
"http://ajaxref.com/lib/jquery/jquery.js"></script>
<script type="text/javascript">
function sendRequest()
{
var options = {success : handleResponse,
type : "GET",
url : "http://ajaxref.com/ch1/sayhello.php"
}
$.ajax(options);
}
function handleResponse(responseXML)
{
$("#responseOutput").html($(responseXML, "message").text());
}
Free download pdf