Check username availability using Ajax/JQuery

I’m loving jQuery now. Yesterday when I was designing a registration page for a client, I decided to use jQuery to check the availability of username to develop my skill. Practice makes a man perfect, isn’t it ?

Although the client site requires searching of username on its database, I am not going to include this here as it depends on the php developer.

Demo : Click here

Download: Click here

So, I’ve created a php file, check.php which will accept “username” and output “taken” if the username is already taken.

[php]
<?php
$taken = array( “hello”, “john”, “david”,”jason” );
$username= $_POST[‘username’];
if(in_array($username,$taken))
echo “taken”;
?>

[/php]

Then the jQuery Part

[javascript]
$(function()
{
$(“#submit”).click(function(){

var username = $(“#username”).val() ;
$(“#result”).html(“<img src=loading.gif”);
args = “username=” + username ;
$.ajax({
url : “check.php”,
data: args,
type: “POST”,
success: function(data) {
if ( data == “taken” )
$(“#result”).text(“The username is already taken”).hide().fadeIn(“slow”);
else
$(“#result”).text(“The username is available”).hide().fadeIn(“slow”);
}
});

});
});
[/javascript]

HTML part

[html]
<input type=”text” id=”username” />
<input type=”button” id=”submit” value=”Check Availability” />
<br />
<br />
<p id=”result”/> </p>

[/html]

I’ve also used a loading.gif file to get a good ajax look.!

Please modify it if you want use it for your own purpose !

One Reply to “Check username availability using Ajax/JQuery”

Leave a Reply

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