Finally the JavaScript updates the HTML display to change the text, add
new elements via the DOM or change CSS styles. This is shown in Figure 4.3.
Figure 4.3: Application data flow in an Ajax request
For this example, let us start with the server-side PHP validation code, in listing 4.1, which will check that
the submitted username is at least four characters long and doesn??™t clash with an existing username.
Listing 4.1: ajax.php: A simple server side validation routine in PHP
function checkUsername($username) {
$existingUsers = array('rasmus', 'zeev', 'andi');
// empty check
if ($username == '') { |#1
return ''; |
} elseif (strlen($username) < 4) { #2
return '
Username is less than 4 characters
';
} elseif (in_array($username, $existingUsers)) { #3
return '
Username already exists
';
} else {
return '
Username is acceptable
';
}
}
if(!class_exists('PHPUnit_Framework_TestCase')) { |#4
$name = isset($_GET['name']) ? $_GET['name'] : ''; |
echo checkUsername(trim($name)); |
} |
(annotation)<#1 No message if there is no username>
(annotation)<#2 Check that the username is long enough>
(annotation)<#3 Check that the username doesn??™t already exist>
Licensed to Menshu You
Pages:
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126