enavu webdevmania tutsvalley psdestination
visit the enavu network
37 Comments Article Title Overlay Article Title

Checking username availability with ajax using jQuery

The time when username availability is checked after the page is normaly processed is long way behind us. Google has it, Yahoo has it and many many more sites have it, ajax username availability checker. So in this tutorial we will make an ajax username availability checker powered with jQuery.

DZoneDiggDesign FloatDeliciousBlinklistRedditFacebookGoogle BuzzTwitterStumbleUponTumblrShare

What are we making here?

nostyle

In the source code there also is a styled version.
styled

Source

Notice: The source includes both styled and non-styled version.

HTML

<input type='text' id='username'> <input type='button' id='check_username_availability' value='Check Availability'>
<div id='username_availability_result'></div>

PHP

//connect to database
mysql_connect('host', 'user', 'pass');
mysql_select_db('database_name');

//get the username
$username = mysql_real_escape_string($_POST['username']);

//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select username from users where username = "'. $username .'"');

//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
	//and we send 0 to the ajax request
	echo 0;
}else{
	//else if it's not bigger then 0, then it's available '
	//and we send 1 to the ajax request
	echo 1;
}

You will need to change these values:

  • host(mysql db host, usualy localhost)
  • user(mysql db username)
  • pass(mysql db password)
  • database_name(mysql db name)
  • username(mysql db table field)
  • users(mysql db table name)

JQuery

$(document).ready(function() {

		//the min chars for username
		var min_chars = 3;

		//result texts
		var characters_error = 'Minimum amount of chars is 3';
		var checking_html = 'Checking...';

		//when button is clicked
		$('#check_username_availability').click(function(){
			//run the character number check
			if($('#username').val().length < min_chars){
				//if it's bellow the minimum show characters_error text '
				$('#username_availability_result').html(characters_error);
			}else{
				//else show the cheking_text and run the function to check
				$('#username_availability_result').html(checking_html);
				check_availability();
			}
		});

  });

//function to check username availability
function check_availability(){

		//get the username
		var username = $('#username').val();

		//use ajax to run the check
		$.post("check_username.php", { username: username },
			function(result){
				//if the result is 1
				if(result == 1){
					//show that the username is available
					$('#username_availability_result').html(username + ' is Available');
				}else{
					//show that the username is NOT available
					$('#username_availability_result').html(username + ' is not Available');
				}
		});

}

Final words

That’s it, easy isn’t it :) . This demo doesn’t have a demonstration page, because it works with mysql database. Sorry about that.

Related posts:

  1. Client side filtering data with jQuery
  2. jQuery and Ajax :) the simple designer way
  3. Simple Fast and Dirty Introduction to jQuery
  4. Top 10 jQuery Snippets (including jquery 1.4)
  5. 10 Awesome jQuery and JavaScript Snippets

Slobodan Kustrimovic

This author has yet to fill his BIO.

Did you absolutely LOVE this article... share it!

Comments

  • Sorry is very useful this tutorial but if i want to have this check automatic could be possible? (without the checking button) beacuse i have seen all the other site that has this kind of tutorial but all said that you have to write a list of all the username that you have registered on you Database… That’s Impossible!!! Thanks for your reply

  • No need to write any lists, the mysql query checks through the usernames inside the users table which is populated when someone signs up.

    If i understand correctly, you want the username check to be fired automatically, so here is how to make it start when someone types in something.

    Just change the

    $(‘#check_username_availability’).click(function(){ …

    into

    $(‘#username’).keyup(function(){ …

  • Cool posting. This username check is one of the easiest I see online. Thanks!

  • You’re welcome :)

  • Thank you so much for this amazing tutorial. However, it did not work for me with Mozilla, I always got user is not available. I tried it in IE and it worked. So, I am going to try and fix function check_availability() in the index.html. I will let u know if I arrive at something.

  • I figured it out. It was not running on Mozilla b.c. I ran it as a file (file:///C:/xampp/htdocs/forms/Check%20User/index.html) rather than a web site (http://localhost/forms/Check%20User/index.html). Really stupid mistake

  • I have a few issues that I’m not sure how to fix.
    When I fire up my form I get a notice “Notice: Undefined index: user_name in”
    in this line [CODE]$username = mysql_real_escape_string($_POST['user_name']);[/CODE]

  • Here is the second issue. The form connects to the ajax file but returns a 1 for every entry I try. The table is empty so the name should be available. Can you explain maybe what I’m doing wrong. The connection to my database is good.
    Thanks

  • Some suggestions and solutions:
    ====================
    1. Resolve jQuery conflicts:
    jq = jQuery.noConflicts();
    jq(document).ready(function(){
    }

    and replace each ‘$’ with ‘jq’.

    2. Other events:
    Use ‘click/keyup/blur’ events on the ‘username’ field itself to have minimum fields

    3. Use instead

    4. PHP – MySQL:
    Select username from table
    $result = mysql_fetch_array(mysql_query(“SELECT username FROM users”));

    # if number of rows fields is bigger than 0 that means it’s NOT available

    Use – if($username == $result['username']) – instead – if(mysql_num_rows($result) > 0)

    ———————————
    @ Tsalagi – I am 100% sure this will solve your problem

  • I’m a complete novice on jquery, exactly where should I paste that code? Is it pasted into the html page or the php page and where exactly on the page should it be placed? Thanks.

  • I understand now, I had to go to jquery.com to figure it out.

  • Will someone please explain to me about the User section where it says that it must be changed to accomodate the server because I don’t see a place in the code that gives me a place to designate the MySQL database name?

  • Tedah: “I don’t see a place in the code that gives me a place to designate the MySQL database name?”

    First lines ->

    //connect to database
    mysql_connect(‘host’, ‘user’, ‘pass’);
    mysql_select_db(‘database_name’); <– database name ??

    Very hard to miss.

  • Novis here! I cannot get this to work. Would someone be willing to take alook at my DB set up to see if it is correct?

    Thanks

  • I’m talking about the area above the JQUERY that lists the six things in the code that need to be modified, specifically “users(mysql db table name)”.

  • The other problem I’m having with this code is, I’m a complete novice and there are no instructions as to where to paste/insert the code such as in the head, body, or in a js page/file and whether or not the page(s) need to be named something particular. Help! Thanks.

  • yeah…its really working…
    thanx 4 posting it.

  • Really nice post…thank you

  • Thanks for the stuff dude

  • Very Nice script, thank you very much.

  • Lovely! Works a charm.

    Thanks buddy.

  • Works like a charm with ASP.NET MVC. Thanks :)

  • Very nice script! thx

  • Very good. thx for sharing. wait for more samples and inline editing.

  • Hi! Thanks for sharing your knowledge! Nice tutorial! I have a question.. it’s possible to check the availability of time (hh:mm) from mysql based on table where we have the time in format 6.00 – 6.30 – 7.30 and so on.. and then, if one is choosed, the next time the script will load without the previous choosed time because it’s already taken? I dont know if you can understand me, my english isn’t really good and it’s hard for me to explain! if you need contact me on my email [email protected]

  • Thanks a lot, very usefull, i like it.
    Regards from Spain.

  • I think it’s possible to change the event that fire the check function, instead of click event on the button you could use the change event on the text area, that way, when the user finishes writing its username and jump to the next element of the form, the script will start and do the checking, i think gmail uses something like that…
    you can as well do the checking on the key up event, for a more “real time” experience, but this may generate a large number of database access, one for each key the user types, that may overload the database server

  • awesome useful script thank you. it was very easy to set up with my CMS.
    Tedah, please go to php.net and learn php before asking a stupid question like that again OR if you dont know how to do something ASK GOOGLE! Thats what its there for and thats where i learned php.

  • Thnx for this post. Its very helpful. I hv modified it to achieve on blur availability.

  • It is really good. . .Working well.

Leave your own!

Sponsors

freedcamp free project management

Popular Articles

fzilla file hosting