- The Challenge: Checking User Input in Real Time
- The Design: Designing a Validator Application
- Putting Together the Validator Application
- Testing Validator
- Giving Validator an Extreme Ajax Makeover
- Summary
Putting Together the Validator Application
Aside from the standard toolkit JavaScript files, including validatekit.js, the Validator application consists of only two components:
- HTML Web page (validator.html)
- PHP server script (ziplookup.php)
Of course, the other major ingredient in the application is the third party location Web service that is responsible for providing the city/state data based upon a ZIP code. Although this service is an important part of the application, it doesn't require a distinct component other than code within the HTML Web page that initiates an Ajax request and code within the PHP server script that handles relaying the response back to the page. This arrangement is necessary because Ajax requests aren't allowed direct access to resources located on other domains.
The next couple of sections explore the Validator Web page and server script in detail in order to fully understand how the application works.
The Validator Web Page
The HTML Web page for the Validator application, validator.html, consists of a series of text box input fields, each with a non-input text field next to it that serves as a display area for help messages. The text boxes are created as input elements, while the help message fields are created as span elements. Figure 7.4 shows the Validator application open in a Web browser with the blank text fields ready for user input and all of the help messages indicating that the fields are missing data.
Figure 7.4 The Validator Web page consists of a series of text box input controls followed by text display areas.
With the layout of the Validator application in mind, as revealed in the figure, check out the HTML code for the body of the Web page:
<body onload="document.getElementById('something').focus()"> <div id="ajaxState" style="display:none; font-style:italic"> </div> <br /> <div> Enter something: <input id="something" type="text" size="32" onblur= "validateNonEmpty(this, document.getElementById('something_help'))" /> <span id="something_help" class="help"></span> </div> <div> Enter an integer: <input id="integer" type="text" size="32" onblur= "validateInteger(this, document.getElementById('integer_help'))" /> <span id="integer_help" class="help"></span> </div> <div> Enter a number: <input id="number" type="text" size="32" onblur= "validateNumber(this, document.getElementById('number_help'))" /> <span id="number_help" class="help"></span> </div> <div> Enter a phone number: <input id="phone" type="text" size="32" onblur= "validatePhone(this, document.getElementById('phone_help'))" /> <span id="phone_help" class="help"></span> </div> <div> Enter an email address: <input id="email" type="text" size="32" onblur= "validateEmail(this, document.getElementById('email_help'))" /> <span id="email_help" class="help"></span> </div> <div> Enter a date: <input id="date" type="text" size="32" onblur= "validateDate(this, document.getElementById('date_help'))" /> <span id="date_help" class="help"></span> </div> <div> Enter a ZIP code: <input id="zipcode" type="text" size="16" onblur="if (validateZipCode(this, document.getElementById('zipcode_help'))) getCityState(this.value)" /> <span id="zipcode_help" class="help"></span> </div> </body>
After the focus is set to the first text box on the page via the onload event handler, the body of the page moves on to creating each of the text box input and associated help message span pairs. There isn't much particularly unusual about any of this code except for the onblur event handler, which gets called when the input focus leaves an input control. So, when the user tabs away from a text box or clicks somewhere else on the page, the text box receives an onblur event notification. This is where you call a function to validate the input value in the text box.
The functions that take care of the validating in the Validator application are all part of the validatekit.js Ajax Toolkit file, which must be imported into the Web page with the following line of code (placed in the head of the page):
<script type="text/javascript" src="validatekit.js"> </script>
Each of the functions provided by this file accept the same two function parameters:
- The input control containing the value to be validated
- The help control used to display help text
To see how these parameters get passed into a validation function, take a look at the code that calls the integer validation function:
validateInteger(this, document.getElementById('integer_help'))
Because the function is called from within the context of the integer text box, you can pass this as the first parameter to the function. The second parameter is then specified using the standard getElementById() function to grab the integer help control, whose ID is integer_help.
If you pay close attention to the help controls on the page, you may notice that each of the span elements is styled to a CSS style class named help. This style class simply changes the color of the font to red (#FF0000) and the style of the font to italic, which makes the help messages jump out a little more on the page. Following is the code for the Validator Web page's internal style sheet, which includes the span.help style class:
<style type="text/css"> div { padding-bottom:5px; } span.help { color:#AA0000; font-style:italic; } </style>
A global div style is included in the style sheet purely to help provide a bit of vertical spacing between the input controls on the page.
Although the Validator internal style sheet is helpful in making the page look a little better, it doesn't do much to help on the Ajax front. The code that initiates Ajax requests for the Validator application is contained in the onblur event handler for the ZIP code text box. Although this code is in the listing you just saw, it's easier to follow if you break it out of the onblur attribute:
if (validateZipCode(this, document.getElementById('zipcode_help'))) getCityState(this.value);
This code first validates the ZIP code input data to see if it is indeed a five-digit number. This is accomplished with the call to the validateZipCode() function. The return value of the function indicates whether the data is valid (true) or invalid (false). If the data is valid, the getCityState() function is called to initiate an Ajax request. Here's the code for this function:
function getCityState(zipCode) { // Display the wait image document.getElementById("zipcode_help").innerHTML = "<img src='wait.gif' alt='Looking up ZIP code...' />"; // Send the Ajax request to load the city/state ajaxSendRequest("GET", "ziplookup.php?zipCode=" + zipCode, handleCityStateRequest); }
Ah, you finally see some of the magic that makes this application look cool. The first task in the getCityState() function is to display the animated "loading" image, wait.gif, in the ZIP code help control. This image will remain displayed until the Ajax request is completed, thereby giving the user a visual cue that something is taking place behind the scenes.
The second task in the getCityState() function is to actually submit the Ajax request, which involves packaging the ZIP code into a URL for the ziplookup.php server script. The handleCityStateRequest() function is specified as the request handler for the ZIP code Ajax request. Here's the code for it:
function handleCityStateRequest() { if (request.readyState == 4 && request.status == 200) { // Store the XML response data var xmlData = request.responseXML; // Display the city/state results if (xmlData != null && getText(xmlData.getElementsByTagName("CITY")[0]) != "") document.getElementById("zipcode_help").innerHTML = "<span style='font-weight:bold'>" + getText(xmlData.getElementsByTagName("CITY")[0]) + ", " + getText(xmlData.getElementsByTagName("STATE")[0]) + "</span>"; else document.getElementById("zipcode_help").innerHTML = "Could not find the ZIP code."; } ajaxUpdateState(); }
The job of this function, which is called when the Ajax request completes, is to extract the city and state from the response data and display them on the page in place of the "loading" image. The city/state data is extracted with a little help from the getText() Ajax Toolkit function, which is located in the domkit.js file. Notice that the XML element names CITY and STATE are used as the basis for accessing the city and state data. Not only is this data extracted, but it is carefully reformatted using HTML code constructed on the fly. If all goes well, the resulting HTML code looks something like this:
<span style='font-weight:bold'>Scottsdale, AZ</span>
Notice that an inline style is applied to the city and state so that they appear in a bold font, which helps to make them distinguishable from normal help text. If there is a problem with the XML data returned from the server, a help message is displayed indicating that the ZIP code could not be found.
That wraps up the code for the Validator Web page. All that's left is to take a quick look at the PHP server script responsible for passing along the ZIP code request to a remote server.
The ZIP Lookup Server Script
Similar to the Picker application from Chapter 4, "Using Ajax to Dynamically Populate Lists: A Stock Picker," Validator requires a script on the server side to sidestep the limitation of not being able to make a direct Ajax client request on a third-party domain. The third-party domain is important because the Validator application relies on it for looking up ZIP codes. The Validator PHP script serves as somewhat of a security proxy by accepting an Ajax request on behalf of the client, retrieving the city/state data from the third-party server, and then responding to the client with the data. In this way, the Ajax request itself is made on your own domain, which is perfectly acceptable given the security constraints of Ajax.
The third-party Web service I'm talking about is webserviceX.net, which offers several XML-based data feeds. The Picker application in Chapter 4 uses this service to obtain live stock quotes, whereas Validator uses it to obtain detailed information about a ZIP code. In this case you specify a ZIP code, and the server responds with an XML document containing detailed information about it, including the city and state associated with it. You've already seen the code within this XML document, but you haven't seen the PHP script that makes it possible to receive the code via an Ajax request. Following is the code for the ziplookup.php server script:
<?php header('Content-Type: text/xml'); // Load the XML location data from the server $xml = html_entity_decode(file_get_contents( "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=" . $_REQUEST['zipCode'])); // Return the XML location data echo $xml; ?>
Keep in mind that the job of this script is to retrieve an XML document from the ZIP code Web service at webserviceX.net, and then simply pass that data along to the client without any modifications. It is then up to the client to do something useful with the XML code, such as display the city and state on the page.
The server script begins by making sure that the response gets treated as XML. It then loads the XML document from the ZIP code Web service, making sure to pass along the zipCode parameter so that the Web service knows which ZIP code to look up. The script concludes by returning the XML data from the script, which serves as the response to the Ajax ZIP code request.
Although I'm sure you're itching to test out the application, let's take a second to test the PHP script by itself. You saw how this is done in earlier chapters by opening PHP scripts directly in a browser—here's a sample URL for testing the ZIPLookUp script:
http://www.yourdomain.com/ziplookup.php?zipCode=94965
Assuming the ziplookup.php file is stored on your server, change the domain to match yours in this line of code and then enter the URL into your Web browser. Figure 7.5 shows the XML response data generated by the PHP script.
Figure 7.5 You can examine the XML ZIP code information returned by the ZIPLookUp PHP script by opening the script directly in a browser.
It's definitely worth experimenting with the ZIP codes passed into the script via the URL to see how they impact the XML data that is returned. You should always test PHP scripts directly in this manner to make sure their results are consistent with what you expected—it's much tougher to diagnose server script problems when all you're looking at is the client Web page.