The Server-Side Routine
In our example here, the server-side routine, checkuser.php, is written in PHP.
Bear in mind, though, that Ajax is pretty much agnostic about what server-side technology is being used - this routine could be in ASP, JSP or a host of other languages. For this reason, we won't go into too much detail over this code - except that, it uses PHP to interrogate a mySQL database user_table to see whether the column user already contains the username that our visitor has tried to add:
checkuser.php
// database connection code
$HOST = "my.database.server";
$DATABASE = "foo";
$USER = "bar";
$PASSWORD = "whatever";
$conn = mysql_connect($HOST,$USER,$PASSWORD);
mysql_select_db($DATABASE,$conn);
// check if the user is already in the database
// the username to test is passed in variable uname
$result = mysql_query("SELECT * FROM user_table WHERE user = '$uname'");
// count matching fields
$count = mysql_num_rows($result);
// if there are any, we can't accept the username
if($count > 0)
{
echo '0'; // failed
} else {
echo '1'; // success!
}
This returned code is checked by our callback routine. You'll recall that we left this empty, but now we can add some code:
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.responseText == '1') {
document.myform.submit();
} else {
alert('That username is already taken. Please choose another');
return false;
}
}
}
Now we need to write our form checking routine. We'll use the submit button's onclick() method to call the routine:
The checkform() routine will first check the nick field to make sure it's not empty, then call our Ajax routine to check the user name:
function checkform()
{
if(document.myform.nick.value='')
{
alert('Please fill in a Nickname');
return false;
}
checkuser();
}
And that's about it. I haven't included a demo here, but please see the tutorial on CAPTCHA, which uses edxactly this technique for form validation.
This site is brand new and so still somewhat under construction.
Why not bookmark it and call back regularly?