check username availability in ajax and php using jquery’s fading effect

In this post,I’ll show you how to make a fancy username availability checking in ajax and php using jquery.When, you check the the username avaiability a fancy message box will show you the message with a little bit of animation. If you are looking for such kind of effect for checking username availability, then this might be right post for you.


View Live Demo

Now let’s check it how to do check the username avaiability in ajax and php using jQuery.

Html Code :

<div >
 User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
 <span id="msgbox" style="display:none"></span>
</div>

As you can see the above the “span” with id “msgbox” will show you the username availability message from ajax.

Css code :

.messagebox{
 position:absolute;
 width:100px;
 margin-left:30px;
 border:1px solid #c93;
 background:#ffc;
 padding:3px;
}
.messageboxok{
 position:absolute;
 width:auto;
 margin-left:30px;
 border:1px solid #349534;
 background:#C9FFCA;
 padding:3px;
 font-weight:bold;
 color:#008000;
}
.messageboxerror{
 position:absolute;
 width:auto;
 margin-left:30px;
 border:1px solid #CC0000;
 background:#F7CBCA;
 padding:3px;
 font-weight:bold;
 color:#CC0000;
}

I’ve defined three different class for three type of different message class “messagebox” for “checking….” message, “messageboxok” and “messageboxerror” class for displaying username available and not available messages.

As you know you can change the attriubutes of the css of the above code but keep in mind that “position” property should be “absolute”.

Javascript code :

First of all, the jQuery library is used,

<script src="jquery.js" type="text/javascript" language="javascript"></script>

And when the focus is moved from the textbox of username the following function is called which call “user_availability.php” through ajax and display the appropriate message with fading effect.

$("#username").blur(function()
{
 //remove all the class add the messagebox classes and start fading
 $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
 //check the username exists or not from ajax
 $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
 {
  if(data=='no') //if username not avaiable
  {
   $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
   {
    //add message and change the class of the box and start fading
    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
   });
  }
  else
  {
   $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
   {
    //add message and change the class of the box and start fading
    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
   });
  }
 });
});

As you can see in the first line, “all” css class is removed from the div displaying the message and then “messagebox” class is added to that that element with adding the text “checking” within the element and displaying with fading effect.

After that, ajax is used to call the PHP file, and when response is received through Ajax then jQuery is used to show the respective message-box with fading effects.

Php Code:

//this varible contains the array of existing users
$existing_users=array('roshan','mike','jason');
//value got from the get metho
$user_name=$_POST['user_name'];
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
 //user name is not available
 echo "no";
}
else
{
  //username available i.e. user name doesn't exists in array
  echo "yes";
}

In the above PHP code, I’ve added three usernames in a array and then check weather that user exists or not in that array and print “yes” or “no” accordingly. The response taken from ajax is used within JavaScript function to display the appropriate message.But, you can use database connection to check the the availability of username in your code.

Download full source

156 thoughts on “check username availability in ajax and php using jquery’s fading effect

  1. I’m confused, What exactly are you trying to do with the database? I guess I don’t understand your question.

  2. Ian

    Hey all,
    i’ve been trying to make it work with the database and its not working. It keeps saying its available when it isn’t. If its possible can anyone email me the fullscript integrated for MySQL database or help me out here?
    Thank You IN ADVANCE =]

  3. Roshan its not working i have configure database but always display same error login details sucks

    what i can do more ?

  4. Can you post the code you have so we can see whats wrong?

  5. I just want to say a big thanks for this great piece of code. I’m sure to get stuck though ๐Ÿ˜‰

    Thanks again!

  6. M. Dubb

    Hi Roshan

    Sorry I never got an email on your reply.
    Thanks.

  7. hi,
    i have a query. plz can u tell me y it is showing the same msg in both condition ie. “username available”. while it is already exists.
    plz plz plz solve my query & also i m using a query to connect it with db.

  8. @bang- this question is already solved in previous comments please look at them to fine the solution..

  9. Roshan
    Thanks a lot for a quick reply but i hav read all of the comments but i didnt find the solution for the same can u plz explain it again for me.

  10. Thaks a lot for wonderful product. Good Free product worth a lot. Thanks Again.

  11. Roshan
    i am getting some plroble. i cudnt connect this code woth db. so that it is showing the same message username already exists.Plz help me out
    Thanks in advance.

  12. Ken

    I have spent countless hours trying to get this to work to no avail. Could you please test this code on with a db query and provide a working user_availability.php file. This was soooo frustrating, I went through soooo many iterations to get this to work. It is fine as is of course but as soon as I edit the php p file with the following it doesnt change its results. The select code and if works for me in a different php script that returns the proper results. You help would be most welcomed.

    $query = ‘SELECT count(*) FROM `user_member` WHERE username=\’mascola\”;
    $result = mysql_query ($query);
    $count = mysql_result ($result,0);

    if($count==1)
    {
    //username already exists
    echo “yes”;
    }
    else
    {
    echo “no”;
    }

  13. All untested but try it anyway;

    $query = “SELECT * FROM table WHERE username=’mascola'” ;
    $result=mysql_query($query) ;
    $num=mysql_num_rows($result) ;

    echo $num.”” ;
    if ($num == 1){
    echo “user exists”;
    }else{
    echo “user does not exist”;
    }

    Cheers

  14. Hi I am Jagadish From Bhaktapur Intrested as your topics. Thanks for your tutorials and can you tell me any site from I can read about ajax more.

  15. Kyriakos Yavrides

    Hello all,
    Great tutorial, I have only one question, How can I check for username inside a form but not by pressing the submit button like the other tutorial but when lost focus like this tutorial and by pressing the submit button to insert the final values to the database?

    Kyriakos

  16. Rushhh

    Thanks Roshan

    My code finally works with mysql, but for some reason It didn’t like the require_once or incude when using it with the connect file, so I just add it in the code and it works. But anyways here is my code.

    [code]
    $host = “localhost”;
    $db_username = “xxxx”;
    $db_password = “xxxx”;
    $db_name = “xxx”;
    $tb_name = “xxxx”;
    mysql_connect($host, $db_username, $db_password) or die (“Can’t connect to Datebase”);
    mysql_select_db($db_name) or die (“Couldn’t successfully connected”);
    $username=$_POST[‘username’];
    $query=(“Select * from $tb_name where username=’$username'”);
    $result= mysql_query($query);
    $num=mysql_num_rows($result);
    if ($num > 0) {//Username already exist
    echo “no”;
    }else{
    echo “yes”;
    }
    [code]

    Thanks again for this tutorial….

  17. TARIQ

    Roshan, Thanks for the lovely code but its not working when I try to use it.
    following is the URL of the web page I have included this on but its not working at all.. Can you take a look at its source code and tell me what I am doing wrong? I will provide you with the details as:
    1) webpage I have embedded the code in:
    http://www.betadistribution.com/register.php
    2) code of my user_availability.php:

  18. Hi TARIQ,

    Does it work on it’s own without your setup?
    I think your page isn’t including everything OR the other code and or code and CSS is interfering.
    Try setting it up step by step – remove all but what you need to make it work then add gradually one by one to find the fault(s).

    I do this whole day – it sometimes takes two or three days to solve one small issue!
    Post back once you get it working on it’s own, also remember to read the docs don’t just copy and paste.

    Cheers

  19. James

    Hey Roshan,

    This is real great once again.
    But I have a problem getting this to work with XMLHTTPRequest when I load external page content into DIVs. Apparently nothing happens when I load my external page into a DIV but when I visit the page alone it works; is there a reason behind this?

    Thank You!

  20. veasna_set

    Dear Sir ,thanks for yur code. But i still have some problems.
    I edited in user_availibility.php as following:
    0){
    //username already exists
    echo “yes”;
    }else{
    echo “no”;
    }
    ?>

    My DB:csc_db
    My table:Tbl_member
    Field name: mem_username

    But i still cannot connect to database. and get right answer. thanks for help

  21. veasna_set

    Oh, I can do it. Thanks

  22. sympathy

    //connect to mysql
    //change user and password to your mySQL name and password
    mysql_connect(“12.XX.WW.WW”,”XXXXX”,”YYYYY”);

    //select which database you want to edit
    mysql_select_db(“XXXXXX”);

    $username = $_POST[‘username’];
    //select the table
    $result = mysql_query(“select * from Alumni where username=$username”);

    if(mysqli_num_rows($result) > 0)
    //{
    //username already exists
    echo โ€œyesโ€;
    }else{
    echo โ€œnoโ€;
    }

    ?>

  23. Sohail

    First of all bundle of thanks for the great work. But I have seen a problem. In case if the field is left empty it says “Username available to register”. I am not expert in Ajax but I have tried to fix this as and it is working fine.

    $(document).ready(function()
    {
    $(“#username”).blur(function()
    {
    //remove all the class add the messagebox classes and start fading
    $(“#msgbox”).removeClass().addClass(‘messagebox’).text(‘Checking…’).fadeIn(“slow”);
    //check the username exists or not from ajax
    $.post(“user_availability.php”,{ user_name:$(this).val() } ,function(data)
    {
    if(data==’no’) //if username not avaiable
    {
    $(“#msgbox”).fadeTo(200,0.1,function() //start fading the messagebox
    {
    //add message and change the class of the box and start fading
    $(this).html(‘This User name Already exists’).addClass(‘messageboxerror’).fadeTo(900,1);
    });
    }
    else if(data==’yes’) //if username avaiable
    {
    $(“#msgbox”).fadeTo(200,0.1,function() //start fading the messagebox
    {
    //add message and change the class of the box and start fading
    $(this).html(‘Username available to register’).addClass(‘messageboxok’).fadeTo(900,1);
    });
    }
    else //if username avaiable
    {
    $(“#msgbox”).fadeTo(200,0.0,function() //start fading the messagebox
    {
    //add message and change the class of the box and start fading
    //$(this).html(‘Username must be entered’).addClass(‘messageboxerror’).fadeTo(900,1);
    });
    }
    });
    });
    });

  24. Take

    Very Good Script, This code work for me:

    include(“db_connect.php”);

    $username=$_POST[‘user_name’];
    $query=(“Select * from tb_users where username=’$username'”);
    $result= mysql_query($query);
    $num=mysql_num_rows($result);
    if ($num > 0) {//Username already exist
    echo “no”;
    }else{
    echo “yes”;
    }

  25. Hey this script is brilliant!

    However, no matter what i do to the user_availablity.php file, it always says user name available. I have tried a few “solutions” from previous comments, but they always say username available, when its not! I have checked and checked again to make sure all details are correct, but it still doesnt work. Any suggestions?

    Thanks a lot

  26. Hi Roshan, Thanks for your tutorial. I found there is lots of people who are confuse and now here I just add some line without changing any code in your post. It have been working very well. So here I am posting my method which I have successfully done.
    <&#63php
    $db_host = "localhost"; //Change your hostname
    $db_user = "user"; //Change Your own database userid
    $db_pass = "password"; // Change your own password
    $db_name = "database"; // And your database name.
    mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
    mysql_select_db($db_name);
    //this varible contains the array of existing users
    $user_name=$_POST[‘user_name’];
    $query="SELECT * from users where username=’$user_name’"; //Here I check the username
    $result=mysql_query($query);
    $existing_users=mysql_fetch_array($result);
    //value got from the get metho
    //checking weather user exists or not in $existing_users array
    if (in_array($user_name, $existing_users))
    {
    //user name is not availble
    echo "no";
    }
    else
    {
    //user name is available
    echo "yes";
    }
    &#63>

  27. Please replace the &#63 to ? thanks

  28. wattsup

    addon: I am receiving the data form the db. here is my code for the php.

    if(isset($_POST[’email_check’])) {
    $email = $_POST[’email_check’];
    //$email = “wattsupnow@cox.net”;

    require_once(‘config.inc.php’);
    require(MYSQL);

    $result = @mysql_query(“SELECT * FROM members WHERE (user_email_one = ‘$email’)”);
    $row_num = mysql_num_rows($result);

    if( $row_num > 0){
    // “unavailable to register”;
    $valid = “no”;
    }else{
    // “available to register”;
    $valid = “yes”;
    };

    echo $valid;
    mysql_close();
    }

    this send the correct echo back. Just the if statement is not working. Thanks for you help.

  29. For those who are having trouble with the script using a database, the easiest way in my opinion is this;
    ==========
    require (“../config.php”);

    $validate_username = @mysql_query(“SELECT * FROM accounts WHERE username='”.$_POST[‘user_name’].”‘ LIMIT 1″);
    $val_output = mysql_fetch_array($validate_username);

    $val_user = $val_output[‘username’];
    $val_mid = $val_output[‘mid’];

    if($val_mid != NULL){
    echo “no”;
    }else{
    echo “yes”;
    }
    ==========

    There is one thing i am looking for, i want the function to also disable/enable the submit button based on the result. I’ve tried to add javascript under or above the following line
    ==[ $(this).html(‘Not Available.’).addClass(‘messageboxerror’).fadeTo(900,1); ]==
    but it seems to just stop it from finishing its fade in and doesnt touch the button.

    any help would be awsome..

    Button name: submit
    Current / Default State: disabled

  30. Dave

    I am having the same problem as many people above where the username is always showing as available, did anyone manage to fix this?

  31. Thanks for the way to check usename availability using javascript. Addressing this issue has enabled user friendly user check before user submits the form. Here is How to check usename availability in asp.net using XMLHTTP. http://dotnetspidor.blogspot.com/2009/03/check-username-availability-using.html

    Thanks a lot.
    Regards,
    Sangam Uprety

  32. AJ

    Great Tutorial Roshan. I have used it in several places. The best part is that using this people can know about the username available or not before they submit the form. Its always annoying to receive a message that says the username is not available while we expect to login.

    Cheers mate!!

  33. webtuto

    i copied all the codes , and it douesnt work for me ๐Ÿ˜ฎ

  34. Joni Carlis

    I use original code and push my nick database into array… it works

    include_once(“includes/config.inc.php”);
    $query = “SELECT nick FROM user”;
    $result = mysql_query (“$query”)
    or die (mysql_error());
    $existing_users = array();
    while ($row=mysql_fetch_array($result)) {
    array_push($existing_users,$row[nick]);
    }
    $user_name=$_POST[‘user_name’];
    //checking weather user exists or not in $existing_users array
    if (in_array($user_name, $existing_users))
    {
    //user name is not available
    echo “no”;
    }
    else
    {
    //username available i.e. user name doesn’t exists in array
    echo “yes”;
    }

  35. Atul

    Thanks for the tutorial man… Should be of great help to me, although i hav 1 question how secure is it? what if i use classes and mysqli to connect to the database if you know what i mean will it become more secure then?..
    Thanx again

  36. Thank you Roshan. This is the script that i was looking for.

  37. nicksource

    Here is a different method of checking an SQL Database, which works for me (all the other didn’t):

    include(‘config.php’);// Connect to database
    $user_name=$_POST[‘user_name’];

    $res=mysql_query(“SELECT COUNT(*) AS usernames FROM members WHERE username=’$user_name'”);
    while($row=mysql_fetch_array($res)){
    $count = $row[“usernames”];
    }

    if($count > 0){
    echo ‘no';
    }else{
    echo ‘yes';
    }

  38. Matt

    If you change blur to keypress it will not respond accurately because it checks before you’re done typing. i.e. if your username is asdf it will check asd

    Does anybody have a way around this?

  39. Hi Roshan,

    Thank you for the script.

    How can I tell the script not to work if length of input is under 5 for example?

  40. John

    A few people mentioned that the script would always say that the name is available. I fixed this by changing the double quotes (“) at the end of the user_availability.php file to single quotes (‘). For whatever reason, the echo was returning weird characters around the yes and no when the double quotes were used.

    If you still have trouble, you can check to see what the php script is really returning by replacing the ‘Username available to register’ in the else clause of the javascript with just the word data without quotes. That way you will see what it is returning. If it is not returning anything, then you have some issues with your user_availability.php script.

  41. Noddy

    Thank you Roshan,
    I just use your code and it is looking great.

    Thanks again
    Noddy

  42. Mayank Bhadauria

    Thank you Roshan

    Your code is really helpful to me..

  43. Dat

    There is a bug in the script.. For example if you type jason it will say unable to register but if you type Jason with the Capital J. You will be able to register it

  44. Dat

    Hi there is a bug in this script i think.. When you enter jason as your username its taken, but when you try to register with Jason with the Capital J its not taken anyway to fix this?

    Thanks

  45. That’s very nice tutorial. but can you show how if with codeigniter. thank’s

  46. HarT

    I don’t know how to make it work in .php file yet
    it always get stuck at the checking process
    Can someone help me with this?

  47. First of all thanks a million for the script!!!!!!

    Second please let me know how can i remove the message box after some time interval?

    Thanks again and keep it up as we need them (the scripts offcourse) ๐Ÿ˜‰ ๐Ÿ˜‰ :)!!!!!!!!!

  48. Parag

    Hi Roshan,

    Can u tell is there any need to install Ajax server..

    Thanks
    Parag

  49. rita

    It doesn’t work, a mean i goes to the datebase and bring the correct field, but the javascript it does not reconised, i dont what is wrong

  50. Parag

    Hi Roshan..

    this code is great.. Thanks!!!

    And thanks to all other commenter as well..

Comments are closed.