check username availability in ajax and php using jquery’s fading effect
- Saturday, April 5, 2008, 16:53
- ajax, how-to, javascript, jquery, php
- 147 comments
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.
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.
Popularity: 38% [?]
Related Posts
» Ajax login validation system in PHP using jQuery
» jQuery is the most popular JavaScript and Ajax Framework
» Register Globals ( register_globals ) “on” security problem in PHP
» Solving European characters (Western charset) problem with Ajax and PHP
147 Comments on “check username availability in ajax and php using jquery’s fading effect”
Trackbacks
- PHP Coding School » Blog Archive » php tips [2008-04-05 17:00:55]
- Css ve Javascript Örnekleri at katodivaihe
- Pages tagged "php"
- Ajax login validation in PHP using jQuery
- Información de Tecnologías»Archivo del blog » Comprobando la disponibilidad de un usuario usando jQuery y Ajax
- Ajax login validation system « Let’s share knowledge
- Mar-22-2009 php links | w3feeds
- Prevent Duplicate SQL Entries - Hot Scripts Forums
- check username availability in ajax and php | ajax username checker
- To procrastinate is to procreate ideas in your brain | qrisper
- Ajax login validation system in PHP using jQuery « Tôi yêu Hà N?i
- 55 Awesome PHP Tutorials for Noobs — ProgrammerFish - Everything that's programmed!
- 55 ??????? PHP ???? ???? ??? ?? « ?????? ????? ????? ?? ???? ? ?????? ????? ? ??? ??
- pligg.com

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.
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 ??
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!!!
Nice to hear that kevin…..
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.
Lewis..This code is just for demonstration…you can customize it according to your comfort…
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.
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…
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
How to use a database with this?
I keep getting errors on in_array with my database function.
Cheers
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
This code is buggy, not sure why.
@Dubb….can you please tell me what is the problem with this code ? where is the bug ? so that I can fix the bug…
I tried the DB solution and it did not work for me… Still looking for the answer.
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….
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
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
@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…
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”;
}
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?
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
How to use check this user name availability using ‘onSubmit’ function
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
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!
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’;
}
Thanks tevan for sharing…good luck….
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.
thanks steve…….thanks to all the other commenters as well…
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.
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...
This script works very nice, thank you very much.
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?
Hi Karls
You need to post your code, so that people can see what is wrong.
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.
$(‘username’).({ backgroundColor:”red” }); to change the background color of username field to red
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]
Ok…here is the code
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”;
}
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]
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.
nice to hear that….
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?
@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..
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.
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
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
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.
@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…
I copied the JQuery code and saved it and then copied the code you provided. It is currently not working.
Any solution to the database section? I tried the suggested ways and it did not work for me.
I’m confused, What exactly are you trying to do with the database? I guess I don’t understand your question.
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 =]
Roshan its not working i have configure database but always display same error login details sucks
what i can do more ?
Can you post the code you have so we can see whats wrong?
I just want to say a big thanks for this great piece of code. I’m sure to get stuck though
Thanks again!
Hi Roshan
Sorry I never got an email on your reply.
Thanks.
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.
@bang- this question is already solved in previous comments please look at them to fine the solution..
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.
Thaks a lot for wonderful product. Good Free product worth a lot. Thanks Again.
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.
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”;
}
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
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.
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
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....
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:
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
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!
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
Oh, I can do it. Thanks
//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”;
}
?>
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);
});
}
});
});
});
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”;
}
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
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.
<?php
$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";
}
?>
Please replace the ? to ? thanks
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.
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
I am having the same problem as many people above where the username is always showing as available, did anyone manage to fix this?
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
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!!
i copied all the codes , and it douesnt work for me
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”;
}
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
Thank you Roshan. This is the script that i was looking for.
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’;
}
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?
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?
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.
Thank you Roshan,
I just use your code and it is looking great.
Thanks again
Noddy
Thank you Roshan
Your code is really helpful to me..
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
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
That’s very nice tutorial. but can you show how if with codeigniter. thank’s
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?
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)
!!!!!!!!!
Hi Roshan,
Can u tell is there any need to install Ajax server..
Thanks
Parag
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
Hi Roshan..
this code is great.. Thanks!!!
And thanks to all other commenter as well..
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…
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”;
}
I copied the JQuery code and saved it and then copied the code you provided. It is currently not working for database.
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”;
}
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?
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. that worked.
@ 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.
nice tutorial. it works fine with me. Good job Roshan.
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
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!
Sid, I am a freelancer. email me boray@pidizayn.com
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.
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.
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
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
Hi Roshan,
Good one..! It was really easy to use, thanks a lot.
I miss this
It’s been 6 days awaiting my comment to approval… how long does it gonna take…?
I really need to solve that out.
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.
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.
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
great post Roshan..
I really Love this jquery plugin..
Thanks for sharing it.. : )
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!
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
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?
try this http://ignati.com/complete-list-of-ajax-username-availability-checker/
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 !!!~!!
Thanks zia!!!….MANY MANY THANKS!…the code works fine!…I LOVE IT!!
great post. now it’s more clear to me about ajax-php then before..
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
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.
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.