Home > Articles > Programming > User Interface (UI)

This chapter is from the book

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

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">
  <br />
    Enter something:
    <input id="something" type="text" size="32" onblur=
document.getElementById('something_help'))" />
    <span id="something_help" class="help"></span>
    Enter an integer:
    <input id="integer" type="text" size="32" onblur=
      document.getElementById('integer_help'))" />
    <span id="integer_help" class="help"></span>
    Enter a number:
    <input id="number" type="text" size="32" onblur=
      document.getElementById('number_help'))" />
    <span id="number_help" class="help"></span>
    Enter a phone number:
    <input id="phone" type="text" size="32" onblur=
      document.getElementById('phone_help'))" />
    <span id="phone_help" class="help"></span>
    Enter an email address:
    <input id="email" type="text" size="32" onblur=
      document.getElementById('email_help'))" />
    <span id="email_help" class="help"></span>
    Enter a date:
    <input id="date" type="text" size="32" onblur=
      document.getElementById('date_help'))" />
    <span id="date_help" class="help"></span>
    Enter a ZIP code:
    <input id="zipcode" type="text" size="16"
      onblur="if (validateZipCode(this,
        getCityState(this.value)" />
    <span id="zipcode_help" class="help"></span>

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; }

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,

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,

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]) +
      document.getElementById("zipcode_help").innerHTML =
        "Could not find the ZIP code.";

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:

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=" .

// 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:


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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020