I received a mail from my reader that asked to me how to implement live username availability checking. So I had prepared a simple and understanding tutorial with changing background color using jQuery and Ajax.
Sample Database
create database table with name “users_detail “
CREATE TABLE IF NOT EXISTS `users_detail` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
PRIMARY KEY (`user_id`)
)
Dumping data for table `users_detail`
INSERT INTO `users_detail` (`user_id`, `username`) VALUES
(1, 'Michael'),
(2, 'Robert'),
(3, 'QuickMySupport');
user_check.php
$(‘#username’).change(function(){} – username is the ID of the input. Using $(“#username”).val(“id”) calling input field value. First checking the value string length max 3 (username.length > 3))
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
<SCRIPT type="text/javascript">
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
$("#username").removeClass("red");
$("#username").addClass("green");
msgbox.html('<img src="yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#username").addClass("red");
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
</SCRIPT>
<div style="margin:50px">
<input type="text" name="username" id="username" />
<span id="status"></span> </div>
db.php
Contains PHP code.
<?php
$mysql_hostname = "localhost";
$mysql_user = "user name";
$mysql_password = "password";
$mysql_database = "database name";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
check_ajax.php
Contains PHP code.
<?php
include('db.php');
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysql_real_escape_string($username);
$sql_check = mysql_query("SELECT user_id FROM users_detail WHERE username='$username'");
if(mysql_num_rows($sql_check))
{
echo '<font color="#cc0000"><STRONG>'.$username.'</STRONG> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
CSS Code
body
{
font-family:Arial, Helvetica, sans-serif
}
#status
{
font-size:11px;
margin-left:10px;
}
.green
{
background-color:#CEFFCE;
}
.red
{
background-color:#FFD9D9;
}