Snippets, Tutorials

Check username availability using AJAX and jQuery

Javascript

$.fn.checkAvailability = function() {
    $("#check-username").click(function() {
    if ( $('#username').attr("value") != '') {
        $('.loading').show();
        var username = $('#username').val().toLowerCase();
        $.get("check-username.php", { username:username } , function(data) { 
            //if username is already taken (FALSE)
             if (data == 0) {
                $('.loading').hide();
                $('.error').remove();
                $('.available').remove();
                $('#check-username').after('<span class="error"></span>');
                $('.error').text('Username is already taken.');
             } else {
                $('.loading').hide();
                $('.error').remove();
                $('.available').remove();
                $('#check-username').after('<span class="available"></span>');
                $('span.available').text('Username is available.');       
            }
        });
    }
});
 
$(document).ready(function() {
    $("#registration").checkAvailability();
});

xHTML

<form action="#" method="post" id="registration">
    <label for="username">Username</label>
    <input type="text" name="username" id="username" maxlength="30" />
    <input type="button" value="Check Availability" id="check-username" />
    <span class="loading"><img src="images/loading.gif" alt="Loading" /></span>
</form>

CSS

.loading {
    display: none;
}
 
.available {
    color: #060;
}
 
.error {
    color: #f00;
}

Backend

In this case, we are using a php script called check-username.php. However, the backend doesn’t have to be in php, it can be in any language .aspx (.NET), .do (Java), .cfm (ColdFusion), etc. The backend script just needs to return either 1 or 0 (True or False). 1 when the username is available and 0 when the username is already taken.

Recommended Books on jQuery

4 thoughts on “Check username availability using AJAX and jQuery

  1. Great Tutorial, however can you post the php source? Apparently mine isn’t returning the proper values.

Comments are closed.

Career Guide for Software Developers