jQuery PHP & MySQL Username Availability Checker

jQuery PHP & MySQL Username Availability Checker

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

This entry was posted in Javascript, PHP, Tutorials, featured, jQuery and tagged , , , , . Bookmark the permalink.
Comments
27 discussions around jQuery PHP & MySQL Username Availability Checker
  1. Henry says:

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

  2. Ashley says:

    @Henry thanks for the kind words!

  3. 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!

  4. Ben Scobie says:

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

  5. arnold says:

    Thanks might be helpful in my future projects :)

  6. Webdeveloper says:

    I’m definitely gonna use this one! Thanks!

  7. Crystal says:

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

  8. Pingback: Servefault.com

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

  10. Ashley says:

    @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.

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

  12. 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

  13. Ashley says:

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

  14. gimsot says:

    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?

  15. Ashley says:

    @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.

  16. parveen chauhan says:

    nice tutorial! sir thanks!!!!!1

  17. Test says:

    Hi Ashley,

    Nice article!!!

    How can i use other events like onblur instead of keyup

  18. bobsoap says:

    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!

  19. Nomi says:

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

  20. MP says:

    How do you check the usernames? What if I want to fill an array with names and check against it?

  21. 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().
    +1

  22. tutu says:

    I can’t retrieve a set usernames from my database. how can i do it with the php page?where should i change?? Can you help me Ashley??

    thanx in advance

  23. Ronald says:

    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().+1
    +1

  24. Excellent, I tried it and it worked like a charm. I`m into a lot of programming for the company I work for.

  25. gary says:

    Hi,
    I want to check if an email exists. I have used this on the email field but if you put an incomplete email it will accept it and show a green tick and border.

  26. Ashley says:

    @ Gary,

    I’d recommend adding javascript email validation to the input field then on the callback if the email is valid run the function to see if the email exists in the database, so you’ll always be checking valid email addresses against the database minimising database connections.

  27. I just recently implemented what you showed here in your blog. It is very affective. I wanted to offer another bit of feedback on how to slow some of the hit on the server (if your validating by email address). If your validating by email address then you can validate on valid email address. Meaning along with 4 characters, if you also check to make sure it’s a valid email BEFORE hitting the server it’ll restrict some of the flow to the server. However you can only do that if it’s a email address that’s being used as the username (which ends up happening a lot, at least in the systems I build).

    Either way it was a great idea and a very nice/clear implementation.

    —–
    http://www.infotechnologist.biz
    http://www.realmofwriting.com

Leave a Reply

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

*

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

Subscribers
1,250
Twitter
510
Comments
1,207
Posts
125