check username availability in ajax and php using jquery’s fading effect
Posted on April 5, 2008
Filed Under ajax, how-to, javascript, jquery, php
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 availble is available
echo “no”;
}
else
{
//user name doesn’t exists
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: 28% [?]
If you like this post then please subscribe to my full RSS feed . You can also subscribe by email and have new posts sent directly to your inbox.
Related Posts
» Ajax login validation system in PHP using jQuery’s animation
» Jquery : Benefits, Examples and Free Ebook
» How to call php from ajax in every second using Jquery
» Register Globals ( register_globals ) “on” security problem in PHP
Comments
34 Responses to “check username availability in ajax and php using jquery’s fading effect”
Leave a Reply




[...] Username availability checking in ajax and php using jquery’s … By Roshan 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. Roshan Bhattarai’s Blog - PHP… - http://roshanbh.com.np [...]
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
[...] Username availability checking in ajax and php using jquery’s fading effect [...]
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…
[...] tagged phpOwn a Wordpress blog? Make monetization easier with the WP Affiliate Pro plugin. Username availability checking in ajax and php usi… saved by 3 others ismellrottenflesh bookmarked on 04/14/08 | [...]
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
[...] time, I’ve showed you how to check user availability in Ajax using jQuery’s fading effect. But I’ve just shown the example without connecting the database and some people have faced [...]
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...