Wrox Home  
Search
Professional Ajax
by Nicholas C. Zakas, Jeremy McPeak, Joe Fawcett
March 2007, Paperback


Defining the HTML Form - No Ajax Required

The first step in creating such interaction is to define the HTML form that will collect the data. This form should stand alone so that it can be used even if Ajax calls aren't possible:

<form method="post" action="Success.php">
    <table>
        <tr>
            <td><label for="txtFirstName">First Name</label></td>
            <td><input type="text" id="txtFirstName" 
			name="txtFirstName" /></td>
        </tr>
        <tr>
            <td><label for="txtLastName">Last Name</label></td>
            <td><input type="text" id="txtLastName" 
			name="txtLastName" /></td>
        </tr>
        <tr>
            <td><label for="txtEmail">E-mail</label></td>
            <td><input type="text" id="txtEmail" name="txtEmail" />
	<img src="error.gif" alt="Error" id="imgEmailError" 
	style="display:none" /></td>
        </tr>
        <tr>
            <td><label for="txtUsername">Username</label></td>
            <td><input type="text" id="txtUsername" name="txtUsername" />
	<img src="error.gif" alt="Error" id="imgUsernameError" 
	style="display:none" /></td>
        </tr>
        <tr>
            <td><label for="txtBirthday">Birthday</label></td>
            <td><input type="text" id="txtBirthday" name="txtBirthday" />
	<img src="error.gif" alt="Error" id="imgBirthdayError" 
	style="display:none" /> (m/d/yyyy)</td>
        </tr>
        <tr>
            <td><label for="selGender">Gender</label></td>
            <td><select id="selGender" name="selGender">
	<option>Male</option></option>Female</option></select></td>
        </tr>
    </table>
    <input type="submit" id="btnSignUp" value="Sign Up!" />
</form>

You should note a few things about this form. First, not all fields will be validated using Ajax calls. The fields for first and last name as well as gender (represented by a combo box) don't require validation. The other fields — for e-mail, user name, and birthday — will make use of Ajax validation. Second, you'll note that these fields have a hidden image after the text box. This image is used only in the event that there is a validation error. Initially the images are hidden, because those browsers without Ajax capabilities should never see them. There is absolutely no JavaScript on this form; all the appropriate functions and event handlers are defined in a separate file.

A single function called validateField() is used to validate each form field. This is possible because each field uses the same validation technique (call the server and wait for a response). The only differences are the types of data being validated and which image to show if validation is unsuccessful.