Tuesday 16 September 2014

Username availability checking in database using Ajax and mysql

Now a days everyone expecting unique username to avoid the username collaboration, for that we have solution, most of site are produce the unique username after we submit the all details, for that we have alternate solution by using AJAX ad PHP, let's see the detailed coding of it. 

username live availability


DOWNLOAD                       LIVE DEMO

DATABASE FILE
db.php here we are used mysqli, because mysql is depreciated.  here 
<?php 
    $db = new mysqli('localhost', 'root', '', '1next2');
?>


DATABASE DETAILS

Database name --> 1next2
Database table name --> usernames

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


AJAX FUNCTION
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/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 > 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

$.ajax({  
    type: "POST",  
    url: "function.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.PHP
the above ajax function is also come ti the index.php file only.
<input type="text" name="username" id="username" style="margin-top:35px;" />&nbsp; &nbsp; 
<span id="status"></span>


No comments:

Post a Comment

© All rights reserved @ 1next2.com