28 May, 2009
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
Love what you've just read? Subscribe to our newsletter to receive tips, resources and special offers related to web development & design.


Hello! Welcome to Web development blog! My name is Ei Sabai and on this blog, I write about web development, mobile app development, latest web technologies and the likes. Read more 


fine example it is useful for newer jQuery Programmer as like me
Great Tutorial, however can you post the php source? Apparently mine isn’t returning the proper values.
this is very helpfulsite for webdeveloper
[...] Check username availability using AJAX and jQuery [...]
i need whole code. I have to implement it with Ajax ModalPopUp Extender