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

Advertisement

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

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

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

  • Gabe wrote on 6 April, 2008, 13:58

    Great usability feature! I hate when I fill out a complete form only to have an error message appear telling me I can’t have that user name.

  • Roshan wrote on 6 April, 2008, 15:39

    Thanks Gabe for your comment…It’s your idea and you told me to have this kind of usability feature in your last comment…do you remember ??

  • Kevin Wong wrote on 7 April, 2008, 16:14

    Great feature! I was just wondering how to make a fancy username availability checking for my online shopping store. Now I get a wonderful user registration form!!!

  • Roshan wrote on 8 April, 2008, 4:43

    Nice to hear that kevin…..

  • Lewis Walsh wrote on 12 April, 2008, 10:46

    Why not change:

    $(“#username”).blur(function()

    to:

    $(“#username”).keypress(function()

    This way the system checks as you type, no need to click way from the box.

  • Roshan wrote on 12 April, 2008, 15:34

    Lewis..This code is just for demonstration…you can customize it according to your comfort…

  • Lewis Walsh wrote on 12 April, 2008, 16:34

    Oh sure, I get that. I personally found clicking away a little counter-intuitive. Just thought this change might help the demo. Either way it’s a great example.

  • Roshan wrote on 12 April, 2008, 17:49

    Thanks lewis, you can hit the tab in keyword as well.What I personally think when filling up the form in any website, people use the tab button to move focus from one element to another…

  • M.Dubb wrote on 13 April, 2008, 10:57

    How to do that with database?
    I have tried to convert the database to an array but no luck.

    ==============

    $query = “SELECT * FROM tablename”;
    $result = mysql_query($query) or die (” . mysql_error());
    while ($row = mysql_fetch_array($result)) {
    if (!empty($row['fieldname']))
    echo ”,$row['fieldname'];
    $usernames = $row['fieldname'];
    }

    //add it to the array…
    $existing_users=array($usernames);

    ==============

    Any ideas?

    Cheers

  • M. Dubb wrote on 13 April, 2008, 17:21

    How to use a database with this?
    I keep getting errors on in_array with my database function.

    Cheers

  • M.Dubb wrote on 14 April, 2008, 0:58

    Open the “user_availability.php” page remove the code add this instead;

    Fixed:

    //connect to database, blah blah

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

    //echo “this is all this system is interested in yes or no ”

    Cheers

  • M.Dubb wrote on 14 April, 2008, 1:39

    This code is buggy, not sure why.

  • Roshan wrote on 14 April, 2008, 6:26

    @Dubb….can you please tell me what is the problem with this code ? where is the bug ? so that I can fix the bug…

  • Kamy wrote on 17 April, 2008, 21:18

    I tried the DB solution and it did not work for me… Still looking for the answer.

  • Roshan wrote on 18 April, 2008, 4:19

    As you can see in the another comment M.Dubb has provided the solutions using database again i’m going to post the same thing..

    //first of all connect to the database

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

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

    That’s it…..try this mechanism….

  • Kamy wrote on 18 April, 2008, 13:49

    Hi Roshan:
    Thank you for quick reply and great tutorials all around.
    I do connect to the db and when I try that script as stand alone php file, I get the correct results.
    However when I hook it to the AJAX file I only get the “Username available to register” msg, no matter if I enter an already existing name or a new one!!
    I noticed M.Dubb said the code was buggy, perhaps that’s what he meant too?

    Greatly appreciate it if I could use your code, as I’ve already integrated in my new project.

    Thanx
    Kamy

  • WhimZefx wrote on 19 April, 2008, 6:13

    Hey Roshan,

    Great script and one I’d certainly like to use. Just one point I noted – If I remove focus from the username input field without typing anything at all, the script fires, does it’s ‘check’ and indicates the username ‘is available’.

    I’m no javascript junkie, so I have no hope in hell of sorting it out – even though I’d imagine it should be quite straightforward. But would you (or anyone else out there) know how to put an if/else statement to say: If nothing entered, “Please provide a username” or something like that?

    Thanks

  • Roshan wrote on 19 April, 2008, 7:32

    @kamy, Is the path of the file is correct ?? Which ajaxfile are you talking about kamy? Can you explain in detail?
    And I’m not sure what but M.Dubb is talking about..he should mention the bug..but he’s even not sure about the bug..

    @WhimZefx – well you can try this if($(“#username”).val()==”)
    //write the code here do something…

  • Pauly H wrote on 21 April, 2008, 8:02

    people trying to use this with a database. This Worked for me.

    $query = “SELECT * FROM table where feildname = ‘$_REQUEST[username]‘”;

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

  • aikidosama wrote on 22 April, 2008, 19:48

    Hi Roshan,

    I try this great ajaxphp script, but something still is failing. I check the user_availability.php and try some tests. I am using 2 tables for a database and I call for the users there, then I insert all into an array. All is fine there. But the POST method is the problem, is always empty. Just here:

    $user_name=$_POST['user_name'];

    In my page:

    Usuario

    And I don’t change anything of the javascript.

    The javascript works because show messages of ‘Checking…’ but always the ‘Username available to register’ and its not.

    What could be the problem?

  • Roshan wrote on 23 April, 2008, 5:19

    try to post the user_name in user_availability.php directly from other page and try to debug it directly..you can find some solution out there

  • guru wrote on 25 April, 2008, 9:12

    How to use check this user name availability using ‘onSubmit’ function

  • Roshan wrote on 25 April, 2008, 10:54

    Dear guru, let’s suppose “frm_register” is the id of the form then you can use

    $(“#frmregister”).submit( …
    instead of the
    $(“#username”).blur( …

    you can view that example in the following post

    http://roshanbh.com.np/2008/04/ajax-login-validation-php-jquery.html

  • tevan wrote on 29 April, 2008, 5:45

    thanks roshan — this is a useful tutorial. after half an hour, I was able to get your code to connect to my database and successfully check against usernames already in the database. to get it to work:

    1. change line 21 of index.html from this:

    $.post(“user_availability.php”,{ user_name:$(this).val() } ,function(data)

    to this:

    $.post(“user_availability.php”,{ username:$(this).val() } ,function(data)

    I just removed the underscore from “username”.

    to connect to a database, replace “user_availability.php” with the following code:

    0)
    {
    //username already exists
    echo ‘yes';
    }
    else
    {
    echo ‘no';
    }
    ?>

    be sure to put in your own connection details in mysqli_connect() and your own table and field names in $query. thanks again roshan and good luck to future readers!

  • tevan wrote on 29 April, 2008, 5:47

    user_availability.php should read as the following (it got cut off above):

    // Developed by Roshan Bhattarai
    // Visit http://roshanbh.com.np for this script and more.
    // This notice MUST stay intact for legal use

    // connect to the database
    $db = mysqli_connect (‘host’, ‘user’, ‘pass’, ‘database’) OR die (‘Could not connect to MySQL: ‘ . mysqli_connect_error() );

    $username = $_POST['username'];
    $username = mysqli_real_escape_string($db, $username);

    $query = “SELECT * FROM users WHERE username = ‘$username'”;

    $result = mysqli_query($db, $query);
    if(mysqli_num_rows($result) > 0)
    {
    //username already exists
    echo ‘yes';
    }
    else
    {
    echo ‘no';
    }

  • Roshan wrote on 29 April, 2008, 8:06

    Thanks tevan for sharing…good luck….

  • Steve wrote on 1 May, 2008, 6:56

    Thanks Roshan and others who have added comments.

    It is great that people share their knowledge and skills.

    Saves the rest of us a fair bit time reinventing the wheel.

  • Roshan wrote on 1 May, 2008, 7:04

    thanks steve…….thanks to all the other commenters as well…

  • nil wrote on 7 May, 2008, 3:27

    your demo is gr8,
    i download the code it’s really cool but
    it shows every time that the name is available though i entered “roshan”, “mike” ,”jason”.

    :(
    plese reply
    thank u.

  • Roshan wrote on 7 May, 2008, 7:02

    The demo is working properly, I’ve a feeling that you’re not running the demo under web server and PHP is not getting parsed…put it inside a local web server…check the demo using the demo site such as http://localhost/demo

  • Pieter wrote on 17 May, 2008, 11:20

    This script works very nice, thank you very much.

  • Karls wrote on 21 May, 2008, 9:45

    Hi!
    Im trying to include this feature!! but connecting to a data base…we can connect and we did everything your and readers teach here..but actually we get just “yes”…. we have tried to set the user_name in php file… and it works there, but after in index.html is not catching the variable result, then always is available…
    We are using PHP 4… do you have idea what’s wrong?

  • Pieter wrote on 22 May, 2008, 6:39

    Hi Karls

    You need to post your code, so that people can see what is wrong.

  • JT wrote on 13 July, 2008, 23:23

    Is there any way to make the form input field change to green or red when it is checked as well. i cannot seem to figure it out. I am more of a database guy.

  • Roshan wrote on 14 July, 2008, 5:44

    $(‘username’).({ backgroundColor:”red” }); to change the background color of username field to red

  • Marty wrote on 15 July, 2008, 21:54

    whoops looks like it dosnt like me :|

    [CODE]
    // connect to the database
    $con = mysql_connect(“localhost”,”my_username”,”my_password”);
    if (!$con) {
    die(‘Could not connect: ‘ . mysql_error());
    }

    mysql_select_db(“My_database”, $con);

    $username = $_GET['user_name'];
    $query = “SELECT * FROM Table where username = ‘” . $username .”‘ “;
    $result = mysql_query($query) or die(mysql_error());

    if(mysql_num_rows($result)>0){
    echo “no”;
    }else{
    //username already exists
    echo “yes”;
    }
    mysql_close($con);
    [/CODE]

  • Keith Glover wrote on 16 July, 2008, 7:38

    Ok…here is the code

  • Keith Glover wrote on 16 July, 2008, 7:39

    Dosn’t like the PHP code I guess

    //this varible contains the array of existing users

    require_once(“../config/connection.php”);
    $username = $_POST['username'];

    $query = “SELECT * FROM coaches where folder_name = ‘$username'”;
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);

    $userexist = $row['folder_name'];

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

  • Fajar Dhumadi wrote on 17 July, 2008, 9:55

    Below database integration way is work for me for fill $existing_users as replacing array demo value.

    Thanks for this valuable code sharing Roshan.

    [CODE]
    connect();
    // Developed by Roshan Bhattarai
    // Visit http://roshanbh.com.np for this script and more.
    // This notice MUST stay intact for legal use

    //this varible contains the array of existing users
    $sql_user = “SELECT acc_username FROM accounts”;
    $rs_user = $db->query($sql_user);
    $existing_users = $db->fetch_array($rs_user);
    //$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 availble
    echo “no”;
    }
    else
    {
    //user name is available
    echo “yes”;
    }
    ?>
    [/CODE]

  • InterestingNews wrote on 25 July, 2008, 1:57

    Thanks a lot.
    I have been struggling for two days with a code a borrowed some where. Make my life easier.
    One New subscriber for you.

  • Roshan wrote on 25 July, 2008, 4:24

    nice to hear that….

  • Michael wrote on 5 August, 2008, 23:17

    Everything is working great, including those comments for interfacing with MySQL DB!

    One question… is there a way I can ECHO, or otherwise print, the resulting “available” username?

    So if someone enters “Frank” — and it is available, i’d like the resulting ‘yes’ results to echo back:

    “Congrats, the username Frank is available!”

    I’ve tried figuring out what variable it is… and even then, how do I insert it into the resulting OK box?

  • Roshan wrote on 6 August, 2008, 4:29

    @Michael – you can do it by returning value like “yes-username” and “no” for non existant. The you can use if condition in no and else condition for yes and split the string and use it according to your requirement..

  • Michael wrote on 8 August, 2008, 0:20

    Thanks for your reply, Roshan. But, my lack of knowledge in javascript seems to be preventing me from figuring this out. I can’t seem to take the $username variable and display it in the msgbox for either condition.

    Not sure how to split the string, I tried editing the yes-username part of user_availability.php but it doesn’t seem to work. Any help would be appreciated, thanks.

  • Julien wrote on 8 August, 2008, 18:48

    Hi all
    I try to use this approach with a servlet/JSP website
    I can search in the database but I don’t know how to return the result
    I need the equivalent for echo “no”
    Could someone help me?
    Thanks

  • Jason Marks wrote on 12 August, 2008, 13:34

    Roshan,

    this script is brilliant! Thank you very much for your hard work and effort, and to all other commenters for their input.

    I am trying to implement this into an sqlite driven project I am working on. How would i use this script to check the usernames (User ID) in the sqlite database? I am no expert in this field but i am a very keen amateur trying to learn more.

    I appreciate any feedback.

    Thank you

  • Bryan wrote on 13 August, 2008, 16:32

    I don’t like this script at all. I have been trying to implement it for 40 minutes and it is still not working. Maybe I am missing something.

  • Roshan wrote on 13 August, 2008, 16:56

    @Bryan – yes I agree that this script is not straight enough.You need to know some aspects and coding of jQuery before using this code…

  • Bryan wrote on 13 August, 2008, 17:15

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

  • Bryan wrote on 14 August, 2008, 14:06

    Any solution to the database section? I tried the suggested ways and it did not work for me.

  • Keith Glover wrote on 14 August, 2008, 19:54

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

  • Ian wrote on 18 August, 2008, 21:32

    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 =]

  • salik wrote on 20 August, 2008, 13:14

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

    what i can do more ?

  • Keith Glover wrote on 21 August, 2008, 22:52

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

  • Sharry wrote on 22 August, 2008, 22:28

    I just want to say a big thanks for this great piece of code. I’m sure to get stuck though ;)

    Thanks again!

  • M. Dubb wrote on 23 August, 2008, 6:54

    Hi Roshan

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

  • bang wrote on 30 September, 2008, 11:27

    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.

  • Roshan wrote on 30 September, 2008, 11:31

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

  • bang wrote on 30 September, 2008, 11:57

    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.

  • jignesh wrote on 1 October, 2008, 17:06

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

  • hello wrote on 3 October, 2008, 9:53

    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.

  • Ken wrote on 13 October, 2008, 19:00

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

  • M. Dubb wrote on 14 October, 2008, 6:08

    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

  • Jagadish Dulal wrote on 2 December, 2008, 2:42

    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.

  • Kyriakos Yavrides wrote on 5 December, 2008, 7:36

    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

  • Rushhh wrote on 10 December, 2008, 11:47

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

  • TARIQ wrote on 10 December, 2008, 14:38

    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:

  • M.Dubb wrote on 10 December, 2008, 16:19

    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

  • James wrote on 12 December, 2008, 22:02

    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!

  • veasna_set wrote on 14 December, 2008, 11:01

    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

  • veasna_set wrote on 15 December, 2008, 9:01

    Oh, I can do it. Thanks

  • sympathy wrote on 23 December, 2008, 0:21

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

    ?>

  • Sohail wrote on 23 December, 2008, 21:31

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

  • Take wrote on 26 December, 2008, 18:52

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

  • Scott wrote on 27 December, 2008, 23:06

    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

  • Jagadishwor wrote on 28 December, 2008, 14:43

    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>

  • Jagadishwor wrote on 28 December, 2008, 14:44

    Please replace the &#63 to ? thanks

  • wattsup wrote on 31 December, 2008, 19:15

    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.

  • Tarquin wrote on 16 February, 2009, 2:50

    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

  • Dave wrote on 14 March, 2009, 21:08

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

  • Sangam Uprety wrote on 16 March, 2009, 6:02

    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

  • AJ wrote on 19 March, 2009, 15:42

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

  • webtuto wrote on 28 March, 2009, 6:17

    i copied all the codes , and it douesnt work for me :o

  • Joni Carlis wrote on 28 March, 2009, 7:06

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

  • Atul wrote on 29 March, 2009, 18:30

    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

  • mehmet wrote on 4 April, 2009, 6:38

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

  • nicksource wrote on 10 April, 2009, 15:19

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

  • Matt wrote on 11 April, 2009, 21:42

    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?

  • Boray Eris wrote on 15 April, 2009, 3:03

    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?

  • John wrote on 15 April, 2009, 21:20

    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.

  • Noddy wrote on 21 April, 2009, 10:16

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

    Thanks again
    Noddy

  • Mayank Bhadauria wrote on 28 April, 2009, 7:02

    Thank you Roshan

    Your code is really helpful to me..

  • Dat wrote on 5 May, 2009, 1:33

    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

  • Dat wrote on 5 May, 2009, 21:01

    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

  • D. Rhoseno wrote on 7 May, 2009, 2:13

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

  • HarT wrote on 11 May, 2009, 6:59

    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?

  • Antonis wrote on 18 May, 2009, 13:35

    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) ;) ;) :)!!!!!!!!!

  • Parag wrote on 21 May, 2009, 6:54

    Hi Roshan,

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

    Thanks
    Parag

  • rita wrote on 21 May, 2009, 21:32

    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

  • Parag wrote on 22 May, 2009, 10:10

    Hi Roshan..

    this code is great.. Thanks!!!

    And thanks to all other commenter as well..

  • Parag wrote on 25 May, 2009, 19:39

    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…

  • majo wrote on 7 June, 2009, 13:59

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

  • manu wrote on 19 June, 2009, 12:34

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

  • manu wrote on 19 June, 2009, 12:57

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

  • Kevin wrote on 20 June, 2009, 14:37

    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?

  • Kevin wrote on 20 June, 2009, 15:09

    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;

  • thanks kevin wrote on 5 July, 2009, 19:12

    thanks kevin. that worked.

  • Kasper wrote on 6 July, 2009, 22:36

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

  • ikin wrote on 9 July, 2009, 13:39

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

  • Shyam wrote on 11 July, 2009, 14:02

    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

  • Sid wrote on 14 July, 2009, 23:29

    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! :-D

  • Boray Eris wrote on 22 July, 2009, 11:26

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

  • yogesh wrote on 22 July, 2009, 18:23

    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.

  • Sean Walsh wrote on 26 July, 2009, 22:13

    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.

  • DEAR wrote on 3 August, 2009, 4:55

    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

  • Mahesh wrote on 7 September, 2009, 15:38

    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

  • J Suresh wrote on 9 September, 2009, 7:26

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

  • lauretta.gs wrote on 11 September, 2009, 17:18

    I miss this

  • lauretta.gs wrote on 14 September, 2009, 17:22

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

    I really need to solve that out.

  • Jon wrote on 18 September, 2009, 11:38

    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.

  • Rob wrote on 1 November, 2009, 17:54

    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.

  • Ivo wrote on 4 November, 2009, 17:13

    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

  • Insurance wrote on 13 November, 2009, 10:19

    great post Roshan..

    I really Love this jquery plugin..

    Thanks for sharing it.. : )

  • Techie Talks wrote on 9 December, 2009, 15:51

    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!

  • sweety wrote on 15 December, 2009, 14:40

    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

  • matvespa wrote on 25 December, 2009, 3:44

    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?

  • zia wrote on 27 December, 2009, 8:12

    try this http://ignati.com/complete-list-of-ajax-username-availability-checker/

  • kiranmai wrote on 31 December, 2009, 7:22

    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 !!!~!!

  • matvespa wrote on 3 January, 2010, 9:48

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

  • saiful103a wrote on 13 January, 2010, 23:15

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

  • Tony wrote on 18 January, 2010, 5:26

    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

  • Tony wrote on 18 January, 2010, 5:31

    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.

  • David Greenberg wrote on 8 February, 2010, 5:14

    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.

  • keerthi wrote on 13 February, 2010, 9:25

    @Roshan Thanx for script..!!!

    @TARIQ Hello TARIQ…

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

  • GB Poker Club wrote on 21 February, 2010, 12:45

    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 :-)

  • dharani wrote on 23 February, 2010, 15:07

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

  • anup sakharee wrote on 27 February, 2010, 10:00

    the above codes are not working….

  • GB Poker Club wrote on 27 February, 2010, 13:41

    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?

  • Ian wrote on 15 March, 2010, 20:59

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

  • Ian wrote on 15 March, 2010, 21:02

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

  • Kalin wrote on 17 April, 2010, 10:55

    Exactly what I needed! Thanks!

Trackbacks

  1. PHP Coding School » Blog Archive » php tips [2008-04-05 17:00:55]
  2. Css ve Javascript Örnekleri at katodivaihe
  3. Pages tagged "php"
  4. Ajax login validation in PHP using jQuery
  5. Información de Tecnologías»Archivo del blog » Comprobando la disponibilidad de un usuario usando jQuery y Ajax
  6. Ajax login validation system « Let’s share knowledge
  7. Mar-22-2009 php links | w3feeds
  8. Prevent Duplicate SQL Entries - Hot Scripts Forums
  9. check username availability in ajax and php | ajax username checker
  10. To procrastinate is to procreate ideas in your brain | qrisper
  11. Ajax login validation system in PHP using jQuery « Tôi yêu Hà N?i
  12. 55 Awesome PHP Tutorials for Noobs — ProgrammerFish - Everything that's programmed!
  13. 55 ??????? PHP ???? ???? ??? ?? « ?????? ????? ????? ?? ???? ? ?????? ????? ? ??? ??
  14. pligg.com
  15. Test d’un champ de formulaire en Ajax - Cyril
Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.