Java Reference
In-Depth Information
Now you're ready to send the request. So, you call the
Ajax.Request()
constructor and pass it the URL
and
options
object.
As the last step in this function, you call the
Ajax.Request()
constructor, prepended by the
new
keyword, and pass the URL to
formvalidator.php
and the
options
object:
new Ajax.Request("ch14_formvalidator.php", options);
}
The
checkEmail()
function is almost identical to
checkUsername()
. First, you retrieve the e‐mail
address from the form and validate it:
function checkEmail(e) {
e.preventDefault();
var emailValue = $("email").value;
if (!emailValue) {
alert("Please enter an email address to check!");
return;
}
Next, you build the
options
object:
var options = {
method: "get",
onSuccess: handleResponse,
parameters: {
email: emailValue
}
};
Once again, you provide the obligatory
method
and
onSuccess
properties, as well as the
parameters
object. You set the
email
parameter property to the e‐mail address from the form.
Then, you issue the request by calling the
Ajax.Request()
constructor:
new Ajax.Request("ch14_formvalidator.php", options);
}
The
handleResponse()
function is not left untouched, but the change is subtle:
function handleResponse(transport) {
var response = transport.responseJSON;
if (response.available) {
alert(response.searchTerm + " is available!");
} else {
alert("We're sorry, but " + response.searchTerm + " is not available.");
}
}
This new version uses Prototype's
responseJSON
property to get the parsed JSON. You can use this
property because
ch14 _ formvalidator.php
's
Content‐Type
header is set to
application/json
. If it