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

    Hi Rita,

    Can u tell me what is the exact problem that you are facing.. Bcoz that Script worked fine for me…. No bugs at all..

    reply in case u need any help…

  2. majo

    Hi,

    I tried all PHP function to check the database in comments, but non of them helped, so I write myself one…very very easy and must work!

    include ‘connection.php'; //connect to db
    $username=$_POST[‘user_name’];
    if(mysql_result(mysql_query(“SELECT COUNT(*) FROM ‘table’ WHERE something=’$username';”), 0)){
    echo “no”; }
    else {
    echo “yes”;
    }

  3. manu

    I copied the JQuery code and saved it and then copied the code you provided. It is currently not working for database.

  4. manu

    I am trying with given script but it’s not working for database give solution

    $query = “SELECT * FROM table where fieldname = ‘{$_POST[‘username’]}’”;

    $result = mysql_query($query);
    if(mysql_num_rows($result)>0){
    //username already exists
    echo “yes”;
    }else{
    echo “no”;
    }

  5. Kevin

    I am always getting back user name is available, so I put some debug into my php script of checking the database and verified it is working. My next step was to put a debug check into the javascript by replacing the avail msg with data.

    if the username exists it returns no however the javascript is not seeing is as no

    Any ideals?

  6. Kevin

    Well a little more brainstorming and I worked it out rather than return yes or no I return a number…

    Here is my code for any one else that is trying to do the same:
    TOP OF SIGN FORM PAGE
    $(document).ready(function()
    {
    $(“#email”).blur(function()
    {
    //remove all the class add the messagebox classes and start fading
    $(“#msgbox”).removeClass().addClass(‘messagebox’).text(‘Checking…’).fadeIn(“slow”);
    //check the email exists or not from ajax
    $.post(“email_availability.php”,{ email:$(this).val() } ,function(data)
    {
    if (data>0) //if email 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 Email address 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( ‘Email available to register’).addClass(‘messageboxok’).fadeTo(900,1);
    });
    }

    });

    });
    });

    FORM FIELD

    CHECK PAGE (email_availability.php)
    include(‘includes/config.php’);

    $email = strtolower($_REQUEST[’email’]);

    $check = mysql_query(“SELECT * FROM `users` WHERE email = ‘”.$email.”‘”)or die(mysql_error());
    $CNumb = mysql_num_rows($check);

    //debug
    //echo “DEBUG: query = SELECT * FROM `users` WHERE email = “.$email.” CNumb = “.$CNumb;

    echo $CNumb;

  7. thanks kevin. that worked.

  8. Kasper

    @ Kevin:
    Make sure the php part of the script is by itself or you have it in a php file with cases.
    An example of cases can be shown here:

    to target either of theese type in the url ?a=form for the form part and ?a=verify to get the validating php script.

  9. ikin

    nice tutorial. it works fine with me. Good job Roshan.

  10. Shyam

    Kevin, that’s a lovely brainstorm I must say. The username availability problem is solved.

    For all those who get username available all the time with this script, please look into Kevin’s code right above my post. It’s awesome

    Thanks,
    Shyam

  11. Sid

    I really need help :(
    I’ve tried all the codes just won’t work ->
    Can someone please modify the code for me

    Database name: mergeit_nz
    Database username: mergeit_user
    Database pass: mergeit_abc123
    Table name: mergeit_login
    Username field: username

    If someone can do that for me please I will be greatfullllllll :)
    THANKS! 😀

  12. Sid, I am a freelancer. email me boray@pidizayn.com

  13. yogesh

    I am placing spaces in the username and tabbing out.. still it says that the message “Usename available to register”. I am pulling the data from MySQL. Please guide.

  14. Sean Walsh

    If you are literally copping and then pasting the code from the page make sure that you replace all the whitespace (ie spaces) and that you make sure quotes are not curly quotes but straight quotes. This will give you errors and may not seem too obvious to some. It’s the only reason I had problem with the code.

  15. DEAR

    hi roshan i watch how u helps other that’s great. dear roshan i want to check the user availability from the button along the username field not from the total form submit button then how can i will do that plz help me. plzzz i wll be very thank full .thanx

  16. Mahesh

    Hi Roshan,

    Can you please give me an example of how to use this script using PDO for database connections. Also, give me an example of how to call stored procedures.

    Thanks

  17. Hi Roshan,
    Good one..! It was really easy to use, thanks a lot.

  18. lauretta.gs

    I miss this

  19. lauretta.gs

    It’s been 6 days awaiting my comment to approval… how long does it gonna take…?

    I really need to solve that out.

  20. Jon

    1) keep up the good work, this is exactly what i have been looking for.
    2) Please I need some help, instead of displaying “Email available to register” when the email is available I would like to display a custom message (text and picture) from an external php page. I would like to know how do i call the external php page.
    Any feedback will be really appreciated.

  21. Rob

    Great program THANKS! Just a few questions.
    1. It appears if you tab out of the field before entering anything the program returns “that name is available”.
    – How would you catch this so that if the user tabs out of the field without entering a username the message “you must enter a user name” would appear?

    2. Secondly, if a username that already exists is entered, is there a way for the script to clear the field box, and place the cursor in that field box so the user can immediately start typing another name? This along with my first questions, will help ensure that #1 the field isnt left blank, and #2 reduces the likelyhood that they continue the form without changing the already existing username. Because at it stands, if the username currently exists, the message “that name already exists” pops up, but the name they entered remains in the field box waiting for them to submit the form.

    If there is a simple fix to either of these solutions, can you post the appropriate code and location to place it?

    Thanks a bunch man, this is a great script, and with a few minor adjustments this can be perfected.

  22. Ivo

    Hi everyone,

    If you copied the code from the website your script won’t work, because this rule is forgotten

    $(document).ready(function()

    Good luck everyone & thnx roshan

  23. great post Roshan..

    I really Love this jquery plugin..

    Thanks for sharing it.. : )

  24. This is the easiest code I have seen. Though there are lot of them who copied the post hope they recognized the author. Thanks for your code!

  25. hi Roshan
    i am totally new in this topic but i think you can help me
    if i want to check the usernames on the server and want list of them what should i do?
    that way i can get more option to choose nice nickname :)
    can you plz mail me that script ?
    thanks in advance

  26. matvespa

    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 UserEmail=’$username'”);
    $result= mysql_query($query);
    $num=mysql_num_rows($result);
    if ($num > 0) {//Username already exist
    echo “no”;
    }else{
    echo “yes”;
    }

    I have declare the connection before the code. But still, with this, even if my username exist, it says “Available to Register”. Why?

  27. Hi

    I saw tha code u wrote , Its really Waste Code I ever seen.. Very Poor Coding …
    Dont post these type of codes and waste Users valuable time !!!~!!

  28. matvespa

    Thanks zia!!!….MANY MANY THANKS!…the code works fine!…I LOVE IT!!

  29. great post. now it’s more clear to me about ajax-php then before..

  30. Tony

    For thos who are having problems with always getting ‘Username is available’, try this to debug:

    Change these two lines
    $(this).html(‘User name available to register’).addClass(‘messageboxok’).fadeTo(900,1);
    $(this).html(‘This User name Already exists’).addClass(‘messageboxerror’).fadeTo(900,1);
    to
    $(this).html(data).addClass(‘messageboxok’).fadeTo(900,1);]
    $(this).html(data).addClass(‘messageboxerror’).fadeTo(900,1);

    and you will see what your php page is actually returning. You can then work out what’s going wrong. FWIW i couldn’t get it to work until i changed the yes/no to 1/0 as advised by kevin as above.

    Useful way to learn how to process an ajax query through a dbase.

    cheers

  31. Tony

    oh, for totally cool effect, I changed the css to this:

    .messagebox{ background:#ffc;}
    .messageboxok{ background:#C9FFCA; color:#008000;}
    .messageboxerror{ background:#F7CBCA; color:#CC0000;}

    Change #msgbox to #username in the script and the input box itself will turn to red or green to show if the username is available or not.

  32. Thanks for posting it. Being new to Ajax, I had to work through a number of — perhaps obvious — user mistakes before I finally got the code working. But now, it works great.

    I also appreciate the code enhancement suggestions from other comments.

  33. keerthi

    @Roshan Thanx for script..!!!

    @TARIQ Hello TARIQ…

    How u used the script to validate both Email and password filed….????

  34. Wow what an amazingly nice bit of script, thanks a lot Roshan.
    I struggled for a while to get it to talk to my database, but Kevin sorted that issue in his past although I still got a minor syntax error but 10 minutes of playing around got it sorted.

    Big thanks to Roshan and Kevin :-)

  35. dharani

    can you modify to test username not contains special characters like %^&****()#@$!. thaqnks

  36. anup sakharee

    the above codes are not working….

  37. Maybe I spoke to soon!
    I speaks to my database and shows correctly if a username is available or not, but now when I submit the form no data is entered in the database!!
    Any ideas?

  38. Ian

    Cleaned up CSS for clarity:

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

    }
    .messageboxerror{
    border:1px solid #CC0000;
    background:#F7CBCA;
    color:#CC0000;
    }

  39. Ian

    And great script. Thank you! Very handy.

    Took me a bit of wading through to figure out how to connect to a DB … why not delete the ones that don’t work from this thread? (i.e., all database solution suggestions before “Pauly H wrote on 21 April, 2008, 8:02″)

  40. Exactly what I needed! Thanks!

Comments are closed.