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">&nbsp;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('&nbsp;<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:&nbsp;</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:&nbsp;</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:&nbsp;</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;
}

Stay updated by subscribing to our weekly newsletter! It's free!

What do I get as a subscriber?

  • Latest posts delivered to your inbox
  • Ways to make money online
  • News regarding web development in general

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Sponsors

29 Replies to "An AJAX (jQuery) Username Availability Checker with PHP Back-end"

  1. The download file isn't valid (the zip). However, very nice and well explained tutorial.

  2. 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.

  3. 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

  4. 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.

  5. 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';
    }

    }
    ?>

  6. 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());
  7. Thanks man!! It works :) Very nice

  8. 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?

    1. 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.

  9. 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.

  10. 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

    1. 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

  11. 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.

  12. 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.

  13. 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.

  14. 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?

    1. @Peter, can you give me the URL address where you have integrated the script? I want to see how you have implemented it.

      1. @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.

        1. @Peter, I am glad to hear that. Good luck!

          1. @Gabriel,

            opps… yes… the BASE with target attribute. in case anyone out there has this problem… just remove the tag and it should work.

  15. Thank you for the code, it works great.

    Is there a way to stop the form from posting if the username chosen is valid?

  16. 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?

  17. 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?

  18. 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.

    1. 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’;
      }

  19. Thanks man :)

    simplest plugin easy to use …

  20. 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?

  21. [...] 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 [...]

  22. 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

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>