AJAX - The Complete Reference

(avery) #1

206 Part II: Applied Ajax^


function sendRequest()
{
var URL = "http://ajaxref.com/ch1/sayhello.php";
var callback = { success:handleResponse };
var transaction = YAHOO.util.Connect.asyncRequest("GET", URL, callback, null);
}
function handleResponse(response)
{
var parsedResponse = response.responseXML;
var msg =
parsedResponse.getElementsByTagName("message")[0].firstChild.nodeValue;
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = msg;
}
</script>
</head>
<body>
<form action="#">
<input type="button" value="Say Hello" onclick="sendRequest();" />
</form>
<br /><br />
<div id="responseOutput"> </div>
</body>
</html>

The example can be viewed online at http://ajaxref.com/ch5/yuihelloworld.html.

First Look at YUI Conveniences
To demonstrate some of the elegance of YUI, we used it to rewrite the ever-present ratings
demo from Chapter 3 that used the POST method to submit your feelings about Ajax. As
previously mentioned, when using the asyncRequest() method, you could pass an
appropriately encoded message payload assuming there is a function like the encodeValue()
available using:

var postData = "rating=" + encodeValue(ratingVal) + "&comment=" +
encodeValue(comment);

YAHOO.util.Connect.asyncRequest("POST", URL, callback, postData);

However, the YUI library provides the same serialization concept that we have explored
previously with their method setForm(). When passed a form object or name/ID
reference to a form, the function will return a string containing the properly encoded name-
value pairs for the data in the form.

/* serialize the contents of the form */
var postData = YAHOO.util.Connect.setForm(form);

However, it is not required to save and pass the form data in this fashion as it is
automatically passed for on the next asyncRequest() method call, as shown here:

YAHOO.util.Connect.setForm(form); /* serialize the contents of the form */
YAHOO.util.Connect.asyncRequest("POST", URL, callback);

though, of course, if you want to be explicit you could save and pass the data as well.
Free download pdf