AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 389


code, but we show the basics here, as it will be used in a proper Ajax example in a second.
Given a value in a variable zip, a regular expression can be used to test it for proper format
and then print an error message if it fails.

var regEx = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
if (!regEx.test(zip))
{
message.innerHTML = "The Zip Code " + zip + " is NOT valid";
return false;
}

While the previous code snippet is perfectly legitimate, it doesn’t really check the true
validity of a U.S. ZIP code, just its format. Sending the entire database of all the valid U.S.
ZIP codes to the browser would be inefficient, but using Ajax, the value could easily be
passed to the server after we check that it’s in the right format to see if it is indeed valid. In
this example, the format is first checked on the client and then a query is triggered to the
server to see if the ZIP is actually real. If it isn’t, an error message is issued; if it is, the city
and state values are populated to ensure the data entered is clean. We present the full client-
side code for a ZIP validation here, and Figure 8-14 shows examples of valid and invalid
entries being made.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 8 : User Interface - Zip Validate</title>
<link rel="stylesheet" href="http://ajaxref.com/ch8/global.css" type=
"text/css" media="screen" />
<style type="text/css" media="screen">
.invalid {color: red; font-weight: bold;}
#spinner {display: none;}
</style>

<script src="http://ajaxref.com/ch8/ajaxtcr.js"
type="text/javascript"></script>
<script type="text/javascript">

function sendRequest(url, payload)
{
var options = {method:"GET",
payload:payload,
onSuccess: handleResponse
};
AjaxTCR.comm.sendRequest(url, options);
}

function handleResponse(response)
{
var data = AjaxTCR.data.decodeJSON(response.xhr.responseText);
if (data.length == 1)
Free download pdf