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

Posted on December 5, 2008, under AJAX, jQuery 

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

Comment via Facebook

comments

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

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

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

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

  4. I have the same problem in Internet explorer

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

    1. already solved it xD the script wasnt in the right directory

  6. dear
    i am use this code is university registration form. check user & name in mysql database.

    1. I am glad you found this script useful! Would you share us the URL? I’d like to see it in action ;-)

      1. if javascript is disabled, will this work? is there a way around it?

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

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

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

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

  7. @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 ;-)

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

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

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

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

  11. 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();
    }

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

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

  14. How to run this on a html file after i had download?

  15. Anyone get this to work in IE?

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


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>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.