Friday 21 August 2015

Username live availability Check using php and Ajax

Username live availability is one of the most important thing the database field, why because mostly we have to different kind of username and unique name for all users. then only we can identify the individual user, so for here we are going to check the database field for already existing username availability. so here we are using php fetch coding and AJAX live check without refreshing of the page.

DATABASE

<?php
$conn = mysql_connect("localhost","root","") or die("Database not connected");
$db=mysql_select_db("phpmvcbug", $conn) or die("Database not connected");
?>

database name is --> mvcbugase

table name is --> usernames

Check Database coding

<?php
include('db.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$sql = mysql_query("select id from usernames where username='$username'");
if(mysql_num_rows($sql))
{
echo '<STRONG>'.$username.'</STRONG> is already in use.';
}
else
{
echo 'OK';
}
}
?>

AJAX

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#username").change(function() 
{ 
var username = $("#username").val();
var msgbox = $("#status");

if(username.length > 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">Checking availability...');

$.ajax({  
    type: "POST",  
    url: "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="available.png" align="absmiddle">');
    }  
    else  
    {  
         $("#username").removeClass("green");
         $("#username").addClass("red");
        msgbox.html(msg);
    }  
   
   });
   } 
   
  }); 

}
else
{
$("#username").addClass("red");
$("#status").html('<font color="#cc0000">Please nter atleast 5 letters</font>');
}
return false;
});

});
</script>

index page

<input type="text" name="username" id="username" style="margin-top:35px;" />&nbsp;
<span id="status"></span>

span id="status" is for show the result of the output.

that's it. for live availability check username using php, mysql, and Ajax. 

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

No comments:

Post a Comment