Java Reference
In-Depth Information
}
.submit {
text-align: right;
}
These rules align the fields to give the form a clean and unified look.
As stated earlier, the hyperlinks are key to the Ajax functionality, because they call JavaScript functions
when clicked. The first function,
checkUsername()
, retrieves the text the user entered into the
Username
field and issues an HTTP request to the server.
This function executes because the user clicked a link. Therefore, you want to prevent the browser from
navigating to the URL specified in its
href
attribute. Even though the URL is the hash (
#
), you still
want to call
preventDefault()
:
function checkUsername(e) {
e.preventDefault();
var userValue = document.getElementById("username").value;
Use the
document.getElementById()
method to find the
<input id="FileName _ username"/>
element
and use its
value
property to retrieve the text typed into the text box. You then check to see if the user
typed any text:
if (!userValue) {
alert("Please enter a user name to check!");
return;
}
If the text box is empty, the function alerts the user to input a username and stops the function from further
processing. The application would make unnecessary requests to the server if the code didn't do this.
Next construct the URL to make the request to the PHP application and assign it to the
url
variable.
Then create an
HttpRequest
object by passing the URL and the
handleResponse()
callback function
to the constructor, and send the request by calling
send()
:
var url = "ch14_formvalidator.php?username=" + userValue;
var request = new HttpRequest(url, handleResponse);
request.send();
}
You look at the
handleResponse()
function later. For now, let's examine the
checkEmail()
function.
Checking the e‐mail address availability is almost identical to the username process. The
checkEmail()
function retrieves the text typed in the Email field and sends that information to the server application:
function checkEmail(e) {
e.preventDefault();
var emailValue = document.getElementById("email").value;
if (!emailValue) {