Did you notice how many sites have a verification tool for the ‘username’ field when you try to register? Many use the power of AJAX to check if the nickname has already been assigned to an existing member. This short tutorial gives you an idea of how you can make such a feature in the pages of your website. We’ll use JavaScript (JQuery) and PHP.
Let’s start creating the page where the visitor will type the “username”:
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>An AJAX Username Verification Tool</TITLE> <META NAME="Keywords" CONTENT="form, username, checker"> <META NAME="Description" CONTENT="An AJAX Username Verification Script"> <script type="text/javascript" src="jquery-1.2.6.min.js"></script> <link rel="stylesheet" type="text/css" href="style.css" />
As you can see the JQuery library and the CSS file (will reveal its contents later) are included. Now let’s continue creating the script that takes the input value and sends it to check.php in order to determine if the username is already in use or not. I will explain you the code in detail below.
<SCRIPT type="text/javascript"> <!-- /* Credits: Bit Repository Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html */ pic1 = new Image(16, 16); pic1.src="loader.gif"; $(document).ready(function(){ $("#username").change(function() { var usr = $("#username").val(); if(usr.length >= 4) { $("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...'); $.ajax({ type: "POST", url: "check.php", data: "username="+ usr, success: function(msg){ $("#status").ajaxComplete(function(event, request, settings){ if(msg == 'OK') { $("#username").removeClass('object_error'); // if necessary $("#username").addClass("object_ok"); $(this).html(' <img src="tick.gif" align="absmiddle">'); } else { $("#username").removeClass('object_ok'); // if necessary $("#username").addClass("object_error"); $(this).html(msg); } }); } }); } else { $("#status").html('<font color="red">' + 'The username should have at least <strong>4</strong> characters.</font>'); $("#username").removeClass('object_ok'); // if necessary $("#username").addClass("object_error"); } }); }); //--> </SCRIPT>
Now, close the HEAD tag and add the form inside the BODY tag:
</HEAD> <BODY> <center> <div align="center"> <h2 align="center">AJAX Username Verification</h2> <center>NOTE: Please type an username and continue filling the other fields. You'll see the validator in action.<br /><br /> Already existing members in this demo: <STRONG>john, michael, terry, steve, donald</STRONG></center><br /><br /> <form> <table width="700" border="0"> <tr> <td width="200"><div align="right">Username: </div></td> <td width="100"><input id="username" size="20" type="text" name="username"></td> <td width="400" align="left"><div id="status"></div></td> </tr> <tr> <td width="200"><div align="right">Password: </div></td> <td width="100"><input size="20" type="text" name="password"></td> <td width="400" align="left"><div id="status"></div></td> </tr> <tr> <td width="200"><div align="right">Confirm Password: </div></td> <td width="100"><input size="20" type="text" name="confirm_password"></td> <td width="400" align="left"><div id="status"></div></td> </tr> </table> </form> </div> </center> </BODY> </HTML>
One of the first things that you should learn about JQuery is the usage of $(document).ready():
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
$(document).ready(function() { // javascript code here });
Inside the function ahove we’ll make use of the change() event. This is like having the onChange event handler in the INPUT tag. As you can see it triggers only for the field having the id equal with “username”:
$("#username").change(function() { // verification code here });
When the user types something in the ‘username’ field and moves to the next fields, the length of the username is checked. If it is smaller then 4 characters, an error will be outputted:
Otherwise, the script will use AJAX to send the value to check.php for verification. If the output will be “OK” a green tick box will show letting the user know that the nickname is not used by someone else. If an already existing user is found, an error would be shown to the user, letting him/her know that the chosen username is already in use by another member.
Another nice thing about this script is that it changes the CSS Class of the input field based on the obtained result. If it’s “OK” the field will have a green border. If it’s an error, the border would be colored with red. This can be achieved by using the .addClass() function. Another function that we should use is .removeClass(), in case we need to remove an existing assigned class and re-assign a new one (could be from .object_error to .object_ok or reverse) to the input object.
Here’s how the check.php should look like:
<?php if(isSet($_POST['username'])) { $usernames = array('john','michael','terry', 'steve', 'donald'); $username = $_POST['username']; if(in_array($username, $usernames)) { echo '<font color="red">The nickname <strong>'.$username.'</strong>'. ' is already in use.</font>'; } else { echo 'OK'; } } ?>
Here’s a version of check.php that connects to the database and verifies if the username is already in the ‘members’ table:
<?php // This is a sample code in case you wish to check the username from a mysql db table if(isSet($_POST['username'])) { $username = $_POST['username']; $dbHost = 'db_host_here'; // usually localhost $dbUsername = 'db_username_here'; $dbPassword = 'db_password_here'; $dbDatabase = 'db_name_here'; $db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server."); mysql_select_db ($dbDatabase, $db) or die ("Could not select database."); $sql_check = mysql_query("select id from members where username='".$username."'") or die(mysql_error()); if(mysql_num_rows($sql_check)) { echo '<font color="red">The nickname <strong>'.$username.'</strong>'. ' is already in use.</font>'; } else { echo 'OK'; } } ?>
style.css
/* Credits: Bit Repository CSS Library: http://www.bitrepository.com/ */ html, body { padding: 0; border: 0px none; font-size: 12px; font-family: Verdana; } table { font-size: 12px; font-family: Verdana; } .object_ok { border: 1px solid green; color: #333333; } .object_error { border: 1px solid #AC3962; color: #333333; } /* Input */ input { margin: 5 5 5 0; padding: 2px; border: 1px solid #999999; border-top-color: #CCCCCC; border-left-color: #CCCCCC; color: #333333; font-size: 13px; -moz-border-radius: 3px; }