There are many times we might want to retrieve some data from the server or database without taking the user away from the current page. One such example of this is when a user is registering for a website and they need to verify if a username is available for use or not. Using an AJAX XMLHttpRequest is a quick and efficient way to check the availability of the username. The javascript XMLHttpRequest retrieves information from the server without using a page refresh.

If you are not familiar with how JavaScript uses a generic XMLHttpRequest function, we would strongly suggest you read one of the many tutorials out there. Once you understand how it works and the different methods employed to do it, you will appreciate the ease of jQuery even that much more.

The first step is to download a current version of jQuery. We prefer to use the minified version. Another option is to load jQuery into your page is to use the Google AJAX Libraries API. We don’t use the other AJAX libraries enough to prefer this method, but we have used it in the past for client sites.

Of course we like things to be pretty, so we would also suggest some good images/icons to represent a valid and invalid username. You can create your own image or simply use Google Images to find a nice free icon set that has something to represent this. We have attached two simple icons that we prefer to use.

To get the document started, we assume that you have jQuery loading somewhere in the head of the document (using which ever method you prefer). We are going to make this simple so we just need to create a form to enter a username. The rules for a username are as follows:

  1. Username can not have whitespace
  2. Username must be at least 3 characters long
  3. Username must be no longer then 24 characters long

Simple Registration Form

</p><br /><br />
<p><form id="registrationForm" action="/test/registrationForm.php" method="post"><br /><br /><br />
<fieldset><br /><br /><br />
<legend>Use form below to register</legend><br /><br /><br />
</fieldset><br /><br /><br />
<dl><br /><br /><br />
<dt><label for="username">Username</label></dt><br /><br /><br />
<dd><br /><br /><br />
<input type="text" id="username" name="username" /><br /><br /><br />
<em>Your username must be alphanumeric, 3-24 characters long, can contain underscores, but no spaces. We recommend that you don't change this unless you really have to.</em><br /><br /><br />
</dd><br /><br /><br />
<dt><label for="passwd">Password</label></dt><br /><br /><br />
<dd><input type="password" id="passwd" name="passwd" /></dd><br /><br /><br />
<dt><label for="passwd-confirm">Confirm Password</label></dt><br /><br /><br />
<dd><input type="password" id="passwd-confirm" name="passwd-confirm" /><br /><br /><br />
<dt></dt><br /><br /><br />
<dd><br /><br /><br />
<input type="submit" id="submitRegistration" value="Register" /><br /><br /><br />
</dd><br /><br /><br />
</dl><br /><br /><br />
</form><br /><br /><br />

Now that we have our form setup, we need to do a few things. Obviously we want to check the username when it is entered (or being entered). Second we will want to have some sort of client side validation to save us from processing an incomplete form. Lastly we will want to submit the form and process the response from the server. Whether you use PHP, ASP, ColdFusion or any other method, it is a good practice to validate the form server side as well. We won’t go into that to much, but is a point worth mentioning.

We prefer to insert the following BEFORE the form. You can put this in a *.js file or you can simply insert it into the page, either works for us. We will need to break the JavaScript into three parts. One function that checks the username, a second function that reads the username input element and initiates username check and a third function to validate and process the form.

Check Username Function

</p><br /><br />
<p><script type="text/javascript" charset="utf-8"><br /><br /><br />
//<![CDATA[<br /><br /><br />
function usernameCheck(username)<br /><br /><br />
{<br /><br /><br />
$.get('/test/usernameCheck.php', { 'username':username }, function(xml) {<br /><br /><br />
$(xml).find('response').each( function() {<br /><br /><br />
var error = $(this).find('error').text();<br /><br /><br />
if ( error == 'false' )<br /><br /><br />
{<br /><br /><br />
var successCheck = $('<span></span>')<br /><br /><br />
.css({<br /><br /><br />
'padding-left':'1em'<br /><br /><br />
})<br /><br /><br />
.html('<img src="/test/images/dialog-ok.png" alt="successful" />Username is available.');<br /><br /><br />
$('input[name=username]').after(successCheck);<br /><br /><br />
}<br /><br /><br />
else<br /><br /><br />
{<br /><br /><br />
var errorCheck = $('<span></span>')<br /><br /><br />
.css({<br /><br /><br />
'padding-left':'1em'<br /><br /><br />
})<br /><br /><br />
.html('<img src="/test/images/dialog-error-small.png" alt="error" />Username is already registered.');<br /><br /><br />
$('input[name=username]').after(errorCheck);<br /><br /><br />
}<br /><br /><br />
});<br /><br /><br />
});<br /><br /><br />
}<br /><br /><br />

The code might look overwhelming right now, but it is actually pretty simple. If we break it down, you will see that the first thing we do inside the  usernameCheck() function is call the jQuery AJAX function $.get. This jQuery function will load a remote page using an HTTP GET request. It only has one requirement (the URL), but also allows for [data], [callback], [type] to be included. We are using both [data] and[callback], with [data] = { ‘username’:username } and [callback] = function(xml). The callback is the function that we want to be executed whenever the data is loaded successfully.

Looking into the function you will see that we are finding each <response> tag in the XML repsponse and inside of that we are looking for the text inside the <error></error> node/element of the XML and setting it to the variable “error”.

If the XML responds that error is “false” we use jQuery to create a <span></span> element with image and text response inside of it indicating the username is available. We then insert the new element we have just created after the form input element for username.

The “else” is doing the same thing, only it is showing the username is not available.

We will add some more components to this later, but for now lets move to the next functions.  These two functions should be triggered after the page loads, so we will be placing them inside the $(function() {}); element which tells jQuery to load them after the page loads. There are other methods to do this same thing (such as $(document).ready(function(){}); so if you are familiar with jQuery you can use the element you feel most comfortable with.

Initiate Username Check

</p><br /><br />
<p>$(function() {<br /><br /><br />
var t;<br /><br /><br />
$('input[name=username]').keyup( function() {<br /><br /><br />
// REMOVE WHITESPACE FROM USERNAME<br /><br /><br />
var username = $('input[name=username]').val();<br /><br /><br />
username = username.replace(/\s/g,'');<br /><br /><br />
$('input[name=username]').val(username);<br /><br /><br />
// IF THE USERNAME VALIDATES, CHECK THE DB<br /><br /><br />
if ( username !== '' &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; ( username.length >= 3 &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; username.length <= 24 ) )<br /><br /><br />
{<br /><br /><br />
if ( typeof(t) != 'undefined' )<br /><br /><br />
{<br /><br /><br />
clearTimeout(t);<br /><br /><br />
}<br /><br /><br />
t = setTimeout( function() { usernameCheck(username) }, 750 );<br /><br /><br />
}<br /><br /><br />
});<br /><br /><br />

You will notice the first variable we define is t. This is going to be used for the setTimeout() function later.

After that declaration you will see we are asking jQuery to watch the keyup event associated with the “username” input field and do “stuff” after each keystroke. We start  by simply asking for the value of the input field. Then we use the javascript replace() function to strip out any whitespace values followed by reinserting the “new” username back into the field.

We don’t want to even check for the username unless it meets the criteria we mentioned earlier, so we use the if() statement to help us validate that part. If the username is blank or if the username is greater then or equal to 3 characters and the username is less then or equal to 24 characters, then we continue to process the username.

We don’t want to bombard our server with a request every time a keystroke is made so we use the setTimeout function to  delay the request by a certain amount of time. In order to do this correctly though, we also need to clear the timeout if another keystroke is made within the delay, in effect starting the timeout over again.

Knowing this, we need to give the setTimeout a variable (t) when we call it. Because we know t may or may not exist, we use the if () statement to check for it. If it is defined, we use clearTimeout() function to remove the setTimeout. We can then set the variable t to a fresh setTimeout delay.

Validate and Submit Form

When the end user submits the form, we want to validate it and if it passes validation, submit the form. I am not going to go into a lot of detail about this as I have already done similar tutorials (see here). In a nutshell, we are just making sure the form is filled out and using AJAX to tell us if we were successful/unsuccessful when submitting form.

</p><br /><br />
<p>$('#submitRegistration').click( function() {<br /><br /><br />
//validate the form and submit<br /><br /><br />
var username = $('input[name=username]').val();<br /><br /><br />
var passwd = $('input[name=passwd]').val();<br /><br /><br />
var passwd-confirm = $('input[name=passwd-confirm]').val();<br /><br /><br />
var registrationData = $('#registrationForm).serializeArray();</p><br /><br />
<p>if ( username === ''  || ( username !== '' &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; ( username.length < 3 || username.length > 24 ) ) )<br /><br /><br />
{<br /><br /><br />
errorMessage.push("Username must have between 3 and 24 characters.");<br /><br /><br />
}<br /><br /><br />
if ( username !== '' &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; /\s/.test( username ) )<br /><br /><br />
{<br /><br /><br />
errorMessage.push("Username can not have any spaces.");<br /><br /><br />
}<br /><br /><br />
if ( passwd != passwd-confirm )<br /><br /><br />
{<br /><br /><br />
errorMessage.push("Password and Password confirmation do not match.");<br /><br /><br />
}</p><br /><br />
<p>if ( errorMessage.length > 0 )<br /><br /><br />
{<br /><br /><br />
showMessage( errorMessage, "error", "alert" );<br /><br /><br />
return false;<br /><br /><br />
}<br /><br /><br />
else<br /><br /><br />
{<br /><br /><br />
$.post('/test/registrationForm.php', registrationData, function(xml) {<br /><br /><br />
$(xml).find('response').each( function() {<br /><br /><br />
var error = $(this).find('error').text();<br /><br /><br />
var returnMessageString = $(this).find('returnMessage').text();<br /><br /><br />
var returnMessage = [];<br /><br /><br />
if ( error == 'false' )<br /><br /><br />
{<br /><br /><br />
returnMessage.push(returnMessageString);<br /><br /><br />
showMessage( returnMessage, "highlight", "info" );<br /><br /><br />
}<br /><br /><br />
else<br /><br /><br />
{<br /><br /><br />
returnMessage.push(returnMessageString);<br /><br /><br />
showMessage( returnMessage, "error", "alert" );<br /><br /><br />
}<br /><br /><br />
});<br /><br /><br />
});<br /><br /><br />
return false;<br /><br /><br />
}<br /><br /><br />
});<br /><br /><br />

So that is our start. You will notice if you run this code that it fails to work properly. What we don’t have is a way to clear out the “response” if it already exists on the page. Because we know where the response should be, we can create a simple check for the response and if it is found, remove it.  You will need to do this in both the usernameCheck function and also the function that sets the timeout.

</p><br /><br />
<p>if ( $('input[name=username]').next('span').length )<br /><br /><br />
{<br /><br /><br />
$('input[name=username]').next('span').remove();<br /><br /><br />
}<br /><br /><br />

Using the length of an element is how we check for the elements existence when using jQuery. Once we find that it does exist, we remove the entire element using the jQuery remove() function.

Lastly, jQuery has some features built in that make our forms prettier. I like to use animation to soften the effect of having elements just appearing BLAM! on the page. We can add a slow fade in effect to the username check to ease the message on the page . We add a diplay=none style to the span and then trigger the jQuery fadeIn() effect to achieve this.

</p><br /><br />
<p>var successCheck = $('<span></span>')<br /><br /><br />
.css({<br /><br /><br />
'display':'none',<br /><br /><br />
'padding-left':'1em'<br /><br /><br />
})<br /><br /><br />
.html('<img src="/test/images/dialog-ok.png" alt="successful" />Username is available.');<br /><br /><br />
$('input[name=username]').after(successCheck);<br /><br /><br />
$(successCheck).fadeIn('slow');<br /><br /><br />

There you have it, a nice jQuery username check.  You can test this out here or you can download the files (all zipped up) and give it a try yourself.

usernameCheck.zip (124KB)
usernameCheck.rar (117KB)