Check username availability using jQuery and PHP

I’m working on a new website. I currently only have a screen where the new users can register. Since I want to make it as easy as possible for a new user to register (partly to avoid having them give up in the first few minutes), I need to take care of the username issue:
When you register somewhere, you have to enter a few things about yourself and though I’m sticking to only username, email address and password it’s still a pain to fill it all in, click submit and get the message that the username is not free.
It’s much easier on the new user, if you immediately give him feedback whether the username he has chosen is still free. And it’s much better, if he doesn’t have to click X times on the “check availability” button.

So basically what I need is a form with a username text field. And whenever the user types in something, I want to give some visual feedback (like changing the color of the text field border) whether this username is available or not.

First I need a form element (in the body):

<form method="post" action="register.php">
	<label for="username">Username</label>
	<input type="text" maxlength="30" name="username" id="username">
	<input type="submit" value="submit">
</form>

Of course such a form with only a username makes no sense, but it’s good enough to explain what I’m doing…

Next, we need to do some jQuery magic (in the head section):

<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
	$('#username').keyup(check_username);
});

function check_username(){
	var username = $('#username').val();
	if(username == '' || username.length < 6){
		$('#username').removeClass("available").removeClass("notavailable");
	}
	else {
		jQuery.ajax({
			type: 'POST',
			url: 'check_username.php',
			data: 'username='+ username,
			cache: false,
			success: function(response){
				if(response == 1){
					$('#username').removeClass("available").addClass("notavailable");
				}
				else {
					$('#username').removeClass("notavailable").addClass("available");
				}
			}
		});
	}
}
</script>

A few comments on this part:

  • I use keyup to install my function because I want the check to happen as the user types. If it creates too much network traffic for your taste or it’s good enough for you to only check the availability when the user leaves this text field, you could use change() or blur().
  • Since in my case the username needs to have at least 6 characters I do not check usernames with less than 6 characters.

As you see I use some CSS classes to change the appearance of the text field based on the availability of the username, here the CSS part:

.notavailable {
    border: 3px #C33 solid !important;
}
.available {
    border: 3px #090 solid !important;
}

Instead of changing the border color, you could also change the background color or show a tick or cross sign…

Now let’s have a look at the last piece: the PHP part on the server, check_username.php (which is called using Ajax):

<?php
$username= mysql_real_escape_string($_REQUEST["username"]);
$con = mysql_connect("xxxxxx","xxxxxx","xxxxxx");
if (!$con)
{
	echo 0;
}
else {
	mysql_select_db("xxxxxx", $con);
	$result = mysql_query("SELECT * FROM users WHERE username='" . $username . "'");
	$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();

That’s it ! And this is how it looks like:
Green border when the user name is available
Red border when the user name is not available

6 thoughts on “Check username availability using jQuery and PHP

  1. Firstly, please stop using the mysql_xxx() functions. They are obsolete. Even the PHP manual is recommending to use alternatives. You should be using either the mysqli_xx() functions or the PDO library. Both of these allow parameterised queries, which negates the need to escape your strings, and provides much much better SQL security into the bargain. Use them.

    Secondly, using !important in your CSS is generally considered poor practice. It is occasionally useful, but most times it is either unnecessary or indicates poor CSS code elsewhere that makes it necessary.

    1. I still use mysql_xxx because I currently use the code from an older software as a basis. But I will move to PDO whenever I actually start doing more stuff on the server.
      Regarding !important: With the code in the blog post, it’s just not required. In the code I have in the software (so before cleaning up the HTML stuff), I do need it because I just currently don’t care about clean stylesheets but rather need to try as many ideas as possible to come to a proof of context.
      So yes, I should have put a big disclaimer in the post. But now I do not need it anymore, since we have your comment 😉

  2. Hi, why i still can submit the form even if the user name is not available?

    any way to solve it? Because i am very new to javascript and php.

    1. You can disable the submit button using jQuery when the username is too short or not available:

      $('input[type=submit]').attr('disabled', 'disabled');

      And enable if the username is available using:

      $('input[type=submit]').removeAttr('disabled');

Leave a Reply

Your email address will not be published. Required fields are marked *