Sunday, January 25, 2009

check username availability in ajax and php using jquery’s fading effect

Html Code :

User Name :
input name="username" type="text" id="username" value="" maxlength="15"/>
id="msgbox" style="display:none">

Css code :
.messagebox{
position:absolute;
width:100px;
margin-left:30px;
border:1px solid #c93;
background:#ffc;
padding:3px;

}
.messageboxok{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #349534;
background:#C9FFCA;
padding:3px;
font-weight:bold;
color:#008000;

}
.messageboxerror{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #CC0000;
background:#F7CBCA;
padding:3px;
font-weight:bold;
color:#CC0000;

}
.messageboxhold{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #CC0000;
background:#F7CBCA;
padding:3px;
font-weight:bold;
color:yellow
;
}

Javascript code :


$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$
("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$
.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='no') //if username not avaiable
{
document.form.username.value=null;
document.form.username.focus();

$
("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$
(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(date=='yes')
{
$
("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$
(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
else if(date=='amit')
{
$
("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{

$
(this).html('Plz enter Username ').addClass('messageboxhold').fadeTo(900,1);
});
}

});
});


Php Code:

$existing_users=array(amit,abhishek,kumar);
$user_name=$_POST['user_name'];
if($user_name==null)
{
echo "amit";
exit();
}
if (in_array($user_name, $existing_users))
{
//user name is not available
echo "no";
}
else
{
//username available i.e. user name doesn't exists in array
echo "yes";
}

1 comment:

jeromeee07 said...

i want it to check the username availability from my database...how can i do that????tnx