An AJAX (jQuery) Username Availability Checker with PHP Back-end

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;
}

Download   View Demo

Comment via Facebook

comments

62 Comments

  1. GabrielGabriel says

    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.

  2. Warz says

    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

  3. Warz says

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

    }
    ?>

  4. GabrielGabriel says

    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());
  5. wimbledon says

    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?

  6. GabrielGabriel says

    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.

  7. xenia_jazz says

    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

  8. Patrick says

    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.

  9. Patrick says

    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.

  10. Patrick says

    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.

  11. Peter says

    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?

  12. Adem says

    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?

  13. Adem says

    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?

  14. Josh Freeman says

    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.

    • Josh Freeman says

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

  15. Mike says

    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?

  16. Matt says

    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

  17. Tsalagi says

    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!

  18. workperfect says

    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″);

  19. lowe says

    Hi, i used your script and I was wondering about the “success” parameter of the $.ajax function. I can seem to store the a value on the ‘msg’ variable after the request has been made.

    Please help…

  20. sajid says

    when I chang the textfield id it is not working…. I want to use this script for validating 2 text fields…… but pls just resolve the problem by making it work with different textfield id like “username2″. I think the rest I can manage

  21. Nancy says

    It works ! thanks a lot
    However when i try to call using thickbox the ajax stop working…
    How?
    Can some 1 help me …

  22. Ghazanfar says

    Hi,

    I am using this script with PHP and MySQL. However, the field keeps on loading for ever after change effect? Is there something wrong with the script?

    Please help..

  23. Ali says

    hi Gabriel,
    1) when I try to download file, the page goes to disconnect.
    2) I copy paste all the codes (you explained) in my new files with same names as you suggested, then I run it. The page opens correctly but the required script doesn’t work properly, neither on typing less than 4 charectors nor on typing the same name which is already in my database.

    Kindly suggest me how can I fix it, please.
    I am waiting enxiously.
    Thanx.

  24. mamositas says

    Hey! Thanks for this nice script!
    ITS WORKING GREAT FOR ALL BROWSERS BUT,
    I get problem with IE browsers. It just doesnt work on IE.. But its everything ok for other browsers… Can someone help me to solve this problem :S

    Thanks

  25. XFreak says

    Hi, ive copied the whole code, and modified it according to my DB in MySQL, and even downloaded a tick.gif and a loader.gif. However when i input the username, it doesnt show me nothing

        • Gabriel C.Gabriel C. says

          You can’t use AJAX if JavaScript is disabled. However, you can create a separate page (could be opened as a popup) and just use there HTML and PHP to see if the username already exists in the database. This will not load asynchronously though. The page needs to refresh. I hope I was clear enough. Just let me know if you have any additional questions!

          • Fadi says

            well u kinda loose the wole point of checking availability if u open a new window ha :)
            how often is javascript disabled? is it as much as flash? can i rely on a javascript code in an html form for essential controls?

          • Gabriel C.Gabriel C. says

            Yes, but it’s better than nothing. Another alternative would be to use IFRAMES in a small portion of your page. I would not worry about it really. I’d put a notice to people that have JavaScript disabled:

            e.g.
            <noscript>This site requires JavaScript to work properly. Please keep it enabled.</noscript>

            The percentage of people disabling JavaScript is around 1-2% as far as I know. Just googled “how many people have js disabled” and found this interesting page: http://stackoverflow.com/questions/121108/how-many-people-disable-javascript

            Good luck 😉

          • Fadi says

            thanks for ur help. i dont know much about jQuery, but im really goodin php andjs. in ur code, the php file check.php only prints back a statement. wat if i want the check.php file to access items in the index file, for examp wat im trying to do: if user selects the option ‘usa’ from the menu ‘countries’, how can i use jQuery to load from a database and add all universities and put them in the selection menu ‘universities’?

  26. Gabriel C.Gabriel C. says

    @Fadi, you can check the Free Dynamic Dependant Dropdown here: http://bit.ly/. It’s free and you can even use it with MySQL database. It doesn’t have yet the feature to work without JS enabled but I will update it very soon 😉

  27. fadi says

    On my website, i’ve set the width of the page to %100, but when someone minmizes the page, content scrambles
    since i have a large table in the middle div and a right and left side div’s. wat i wanna do is tell the browser when page is minimized to keep the width the same and use scroll. i tried doing this but setting the width to 1400 for example, but with different screens it wont be exact so i need %100. can anyone help?

  28. TROY says

    Do u have the same sample with other input texts like password, password confirmation, email checking in mysql and email confirmation check?

  29. Scott says

    Hey great script!

    How would you go about modifying the code so that it can be used on a page with multiple forms instead of just one?

    Thanks!!

    • Gabriel C.Gabriel C. says

      You have to duplicate the code from $("#username").change(function() { [....] }); and put unique IDs. Currently, there are 2 used: ‘username’ and ‘status’. Make new elements that have different IDs such as ’email’ and ‘status_two’. So it will be like $("#email").change(function() { [....] });! You can put next to the email field an empty DIV: <div id="status_two"></div> then rename ‘#status’ (from the duplicated code’) to ‘#status_two’.

  30. says

    Great post for an ajax newb.

    In case anyone wants a sql-preventing version of the db version: here’s my quick and dirty one:

    if(isSet($_REQUEST['username']))
    {
    $username = $_REQUEST['username'];

    //CHECKS FOR UNIQUE username
    $con = new mysqli($dbhost,$dbusername,$dbpassword,$database);
    $query = "SELECT userid FROM user WHERE username=? OR email=?";
    $sth = $con->prepare($query);
    $sth->bind_param("ss", $username, $username); //s – string, d-int
    $sth->execute();
    $sth->bind_result($userid);
    $sth->store_result();
    $numresults = $sth->num_rows;
    if ($numresults>0) {
    echo '<font color="red">The nickname <strong>'.$username.'</strong>'.
    ' is already in use.</font>';
    } else {
    echo '&nbsp;<img src="/images/tick.gif" align="absmiddle">&nbsp;Available';
    }
    $sth->close();
    $con->close();
    }

  31. roland says

    Thanks! I’m trying to use the code for coupon code submission form (if coupon code is in the db valid), but I can’t disable the submit on a form so just when valid code is input can users submit the form. here is the page http://bit.ly/fi5XOj

  32. Jerry says

    Hi Guyz!….
    I really need your idea here..
    In my webpage, nothing really happens…
    Am I Forgetting something?

Trackbacks

  1. […] 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 […]

Leave a Reply

Your email address will not be published. Required fields are marked *