jQuery PHP & MySQL Username Availability Checker

19 September 2009| 19 Comments| Print

I was reading Nettuts.com this week and saw the post by Matt Vickers on checking the availability of a username with Mootools. I tend not to use Mootools so i thought I’d replicate the technique using jQuery. The code degrades gracefully if JavaScript is disabled, it is advised that you always check the username against the database again, just before you add any data to the database.

username

The JavaScript

  1. So to start with we have our jQuery on document ready function, within this we have an event listener .keyup function which when triggered runs the function ‘username_check’.
  2. Within the ‘username_check’ function we firstly assign the variable ‘username’ to the value of the input field with the id #username.
  3. We now run a few checks that the username input field isn’t empty and that its 4 or more characters in length. If everything is ok and the username variable is over 4 characters we can go ahead and make the ajax request.

Its worth noting that because were checking the username against the database on keyUp we’re making a unique request each time. To help limit these requests we check that the username is more than 4 characters before perfoming an ajax request.

console


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
$('#username').keyup(username_check);
});

function username_check(){

var username = $('#username').val();

if(username == "" || username.length < 4){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
}else{

jQuery.ajax({
   type: "POST",
   url: "check.php",
   data: 'username='+ username,
   cache: false,
   success: function(response){
if(response == 1){
	$('#username').css('border', '3px #C33 solid');
	$('#tick').hide();
	$('#cross').fadeIn();
	}else{
	$('#username').css('border', '3px #090 solid');
	$('#cross').hide();
	$('#tick').fadeIn();
	     }

}
});
}

}

</script>

Looking at ‘check.php’

This is the code that checks the database to see if the username exists or not. dbConnector.php is the database connection class that i use in all my projects and is in the download of the project files.

The first thing we do is trim any white space and convert the string to lowercase. i’ve ensured that the usernames in the database are all lowercase. So the usernames aren’t case sensitive when a user types one in to the box.

IMPORTANT! because we’re handling unknown user generated data we have to use the mysql_escape_string() function to stop SQL injection and to strip any unwanted chars

Notice that i have omitted the last php tag. If a page contains only PHP code, best practice is to omit the PHP end tag ( ?> ). PHP does not require the end tag in PHP only pages.

Including the end tag can cause unwanted injection of trailing white spaces which can cause header already sent errors.

<?php
include("dbConnector.php");
$connector = new DbConnector();

$username = trim(strtolower($_POST['username']));
$username = mysql_escape_string($username);

$query = "SELECT username FROM usernameCheck WHERE username = '$username' LIMIT 1";
$result = $connector->query($query);
$num = mysql_num_rows($result);

echo $num;
mysql_close();

The HTML

Here’s the input form field and the two images.


Username: <input name="username" id="username" type="text" />
<img id="tick" src="tick.png" width="16" height="16"/>
<img id="cross" src="cross.png" width="16" height="16"/>

The CSS

Here’s the basic style to format the username input field, and to hide the tick and cross image.

#username{
	padding:3px;
	font-size:18px;
	border:3px #CCC solid;
}

#tick{display:none}
#cross{display:none}

demodownload

19 Comments

  • Henry

    It’s always a pleasure coming to this site and learn something. Keep it up Ashley.

  • Ashley (author)

    @Henry thanks for the kind words!

  • Juarez P. A. Filho

    Wow… I liked it so much. Simple and easy to use, but I think make Ajax requests in each letter typed by user is not so good, even after 4 letters, I prefer use in onblur event or even in submit form.
    mysql_escape_string is a nice tip and we can’t forget about use it. Another cool thing I didn’t know is omit the PHP end tag is a best practice.
    Thanks a lot! Cheers!

  • Ben Scobie

    Thank you very much, much better than my current way of checking :)

  • arnold

    Thanks might be helpful in my future projects :)

  • Webdeveloper

    I’m definitely gonna use this one! Thanks!

  • Crystal

    Great tutorial! This complete newbie was able to implement it on a new project, thank you so much!

  • Servefault.com

    jQuery PHP & MySQL Username Availability Checker | Papermashup.com…

    Thank you for submitting this cool story – Trackback from Servefault.com…

  • factoringcompare.com

    Great work. Could you show how to use with asp?

  • Ashley (author)

    @factoringcompare I wish i could show you how to use it with ASP however i don’t have any experience using ASP – If anyone know how to use it with ASP,feel free to post a link here, or show us some code.

  • factoringcompare.com

    The work around could be to use PHP. Can you show me how to connect to an Access database using check.php?

  • factoringcompare.com

    Hi Ashley,

    Done it! ASP code to connect to DB.


    <%
    Dim rsUser__MMColParam
    rsUser__MMColParam = "1"
    If (Request.Form("username") “”) Then
    rsUser__MMColParam = Request.Form(“username”)
    End If
    %>

    1

  • Ashley (author)

    Good stuff! thanks for posting it also. Sorry i couldn’t have been more helpful, im a PHP programmer.

  • gimsot

    Hi Ashley, thanks for this tutorial, i’ts work on my project :) ..
    But how about with the submit button? If the username unavailabe, I was able to process the form. Does anyone can help?

  • Ashley (author)

    @gimsot when you submit the form you will need to do an additional check against the db in your PHP code that adds the user to the database. Let me know if that makes sense.

  • parveen chauhan

    nice tutorial! sir thanks!!!!!1

  • Test

    Hi Ashley,

    Nice article!!!

    How can i use other events like onblur instead of keyup

  • bobsoap

    Great write-up, thanks for sharing. I already put it to good use and I’d like to add a tiny performance issue that I came across – and fixed:

    Sometimes, when you type very fast, and it switches the cross for the checkmark or vice-versa, it liked to “skip” to hide() the old icon for me, and I ended up having both icons showing next to each other. I’m assuming this can happen when the routines overlap, especially when you add in more than just hide() and fadeIn() like I did. For example, I am also filling a nice message into a notice box with html() before I call hide() and fadeIn().

    To fix this, I simply added the fadeIn() inside of a function of hide(). My logic was that when it ges reduced to a single function, it’s less likely that it gets skipped when you type fast. It works so far for me.

    On line 25 of your above code, you have


    $('#tick').hide();
    $('#cross').fadeIn();

    …and I changed that to


    $('#tick').hide(100, function() {
    $(this).parent().find('#cross').fadeIn(400);
    });

    Same for the ELSE part.

    It’s only a minor thing but I hope it helps. Thanks again Ashley for your great post!

  • Nomi

    hey Ashley, good stuff man.. i just came across your site and its very useful … keep it up

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.