An AJAX (jQuery) Username Availability Checker with PHP Back-end
Posted on December 5, 2008, Filled under AJAX, JQuery,
Bookmark it
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;
}


Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- December 5, 2008
- article by Gabriel C.
- 33 comments
Sponsors
Related Posts
-
Validate (input) usernameat August 29, 2008 with 2 comments
-
Simple AJAX Contact Form with jQuery and PHP Validationat September 2, 2008 with 209 comments
-
How to extract username from an e-mail address stringat September 5, 2008 with 2 comments
-
AJAX Contact Form with CAPTCHA, Realtime Validator and PHP Backendat February 8, 2010 with 71 comments
-
How to Implement a jQuery AJAX Login Form into a Modal Boxat April 24, 2009 with 37 comments


33 Replies to "An AJAX (jQuery) Username Availability Checker with PHP Back-end"
December 23, 2008 at 2:42 PM
The download file isn't valid (the zip). However, very nice and well explained tutorial.
December 24, 2008 at 2:44 AM
Thanks! The ZIP seems valid. I've also tried to extract the files using WinRar and WinAce and it worked. Please re-download the file and try to unzip it again. I have used WinZip 12.0 to archive the files.
December 26, 2008 at 7:23 AM
Hey, when I use this script I get this error after writing a username with more than 4 characters:
Parse error: syntax error, unexpected T_STRING in /home/pengera/public_html/username_checker/check.php on line 22
I went into the script and it says on line 22:
echo '<font color="red">The nickname <STRONG>'.$username.'</STRONG> is already in use.</font>';
Do you know what is wrong?
Thanks
December 26, 2008 at 7:57 AM
You have modified the original script. That code (which works fine) is on line 10 in the initial check.php. Here's an address with detailed explanations regarding this parse error::
http://www.parse-error-unexpected-t-string.com/
Let me know if you can manage to fix this.
December 26, 2008 at 1:37 PM
Yes the original works fine, but I am using the database code instead to get values from my database. It is a table called users and has id and username in it.
<?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 = 'localhost'; // usually localhost
$dbUsername = 'pengera_penger';
$dbPassword = 'xxxxxxxxxxxx';
$dbDatabase = 'pengera_penger';
$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 users 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';
}
}
?>
December 26, 2008 at 2:32 PM
Oops, you need to add a double quote after username=’".$username."’
The new line should be like this:
$sql_check = mysql_query("select id from members where username='".$username."'") or die(mysql_error());December 27, 2008 at 6:42 AM
Thanks man!! It works
Very nice
January 10, 2009 at 12:51 PM
hey webmaster,
I get this error:
syntax error, unexpected $end in /home/mysite/public_html/beta/check.php on line 26
But when I check the line, it's else.
What am I doing wrong?
September 23, 2009 at 4:41 AM
I believe you are using the mysql code.
Add a curly bracket `}`at the end of the code just before closing “?>”.
The problem will be resolved.
January 15, 2009 at 5:25 PM
If you're using the database code to get the value check the previous comment. It will help you to solve the issue. If you're not then you must have changed the original script. To have a workable demo, make sure to use the code from the current tutorial.
March 1, 2009 at 2:19 AM
The code is awesome, but there seems to be an error while using on IE. I’ve only made a few adjustments to code – check.php includes database check which is working. On the input for username, if I use one of my auto-completes on IE and either click on different input or tab, it doesn’t seem to work. Autocompletes do work on other browsers.
Any ideas on workarounds for this?
TIA
March 10, 2009 at 1:30 PM
The username checker works with JQuery. If your auto completer uses another library (MooTools, Prototype etc.) then you need to remove any conflict between them( the ‘$’ shortcut). Consider checking the following URL: http://docs.jquery.com/Using_jQuery_with_Other_Libraries
May 4, 2009 at 10:07 PM
how can i add this regex to the code /^[a-zA-Z0-9_\-]+$/ i want to check to make user only a-z 0-9 and _- are allowed.
May 5, 2009 at 12:27 AM
His are regex hack if anyone needs it. i changed this line
if(usr.length >= 4){
to
if (/^[\w]{4,15}$/.test(usr)) {
which mean only word characters a-z or 0-9 and min 4 chr and max 15.
May 5, 2009 at 12:29 AM
I just thought of a feature that should be added, there should be a way to disable the submit button on a form until a valid usernme is input.
July 19, 2009 at 3:09 AM
Hi Gabriel,
Thanks for the wonderful script. I got an unique problem.
I download the script and installed into my webserver and everything seems okay (tested and linked to my DB and it works like how it should). But when I tried to integrated into my website and tried to test it, it kept show “checking availability” forever.
Any idea?
July 20, 2009 at 12:19 PM
@Peter, can you give me the URL address where you have integrated the script? I want to see how you have implemented it.
July 20, 2009 at 2:42 PM
@Gabriel,
I think I found the problem after 2 hours of debugging.
In my webpage, the problem was an inclusion of tag which upset the entire script.
July 20, 2009 at 4:03 PM
@Peter, I am glad to hear that. Good luck!
July 20, 2009 at 6:01 PM
@Gabriel,
opps… yes… the BASE with target attribute. in case anyone out there has this problem… just remove the tag and it should work.
August 14, 2009 at 5:06 PM
Thank you for the code, it works great.
Is there a way to stop the form from posting if the username chosen is valid?
August 25, 2009 at 4:02 PM
Hello,
I have a problem, helps to Do?
I’d like to send extra data check.php page
check.php
$ username = $ _POST [ 'username'];
$ my_data = $ _POST [ 'mydata'];
index.php
$. ajax ((
type: “POST”,
url: “check.php”
data: “username =” + usr,
success: function (msg) (
$ my_data “$ my_extra_data”;
How to add data in the field?
August 31, 2009 at 1:43 PM
Please help
Briefly on issues
index.php
data: “username=”+ usr+”&my_data=”+adem,
check.php
$my_data = $ _POST['my_data'];
Not working
What’s wrong?
October 12, 2009 at 11:52 AM
I tried this code out and when I inserted some data into a sql table, then went back to the page with this and wrote the name that is already in, it says it’s Available. Doesnt seem to be checking.
October 12, 2009 at 12:38 PM
Well forget my above post as it doesnt really matter now, I think i had a few mistakes in my javascript. I went over it again and seems to be good.
If anyoen wants to use the php in an OO fashion here is the code:
/* Select queries return a resultset */
if ($results = $db->query(“SELECT * FROM usernametable WHERE username=’$name’”)) {
$rows = $results->num_rows;
}
if ($rows>0)
{
echo ‘name in use’;
}
else
{
echo ‘OK’;
}
October 14, 2009 at 6:52 AM
Thanks man
simplest plugin easy to use …
October 25, 2009 at 8:10 AM
Great script, but I wanted to modify it.
I have change the function from .change to .keypress so that the check can be done as the user types, like on a Twitter registration.
It only semi works though, in that it only reacts to the previous key press:
If I type ‘mike’ – it shows ‘The username should have at least 4 characters’
I have to type 5 letters for the message to change to OK, so I can type’mike2′ but it is actually checking for ‘mike’ in the database.
does anyone know of a fix for this?
December 29, 2009 at 4:33 AM
[...] Nu am reusit sa fac confirmarea parolei cu ajax. am folosit acest tutorial pentru celelalte campuri An AJAX (JQuery) Username Availability Checker with PHP Back-end pentru confirmarea parolelei am 2 variabile 'pass1' si 'pass2' si trebuie sa afiseze mesajul in [...]
February 1, 2010 at 6:17 AM
Im a little confused as you have not put in code for the submit button, what would be the attributes for the form tag, method=post ? and what would be the action, would it be back on to itself? im just asking because i assume thats how the php would work after a submit
thanks
February 12, 2010 at 9:49 PM
Thanx for Script…:)
March 1, 2010 at 8:23 AM
Remarkable! It works right from the unzip and a few changes to look to my database. I spent 2 days following bad tutorials and downloading bad source code. KUDOS!
March 4, 2010 at 1:21 AM
Nice!very useful.Thank You for posting this.:D
God Bless./m\
March 11, 2010 at 6:19 AM
I’m having problems with the jQuery Maskedinput, when active field validation crashes. How to solve?
jQuery (document). ready (function () (
jQuery ( “# phone”). mask ( “(99) 9999-9999″);