Saturday, May 17, 2014

Check Username availability in PHP using Ajax

In this article i am going to show how to check Check Username availability in PHP using Ajax.

Lets take a look.



PHP Function

    <?php
include("conn.php");

    if(isset($_POST['username'])){
        $user = $_POST['username'];//Get entered username
        $res = mysql_query("SELECT * FROM users WHERE username='$user'");
        $count = mysql_num_rows($res);//Get total num of users list for entered username
        if($count >= 1){
            echo "Not Available";//Show result if not available
        }else{
            echo "Available";//Show result if available
        }
    }
?>

Database Connection

  <?php
$connection=mysql_connect("localhost","root","");
$db=mysql_select_db("database",$connection);

// Check connection
if (!$connection) {
    die('Could not connect: ' . mysql_error());
}
 
?>

HTML Form

<form method="post" action="#">
  <input type="text" id="user" name="username" value="" placeholder="Enter your Username">
  <span id="response"></span>
</form>

JQuery Function

<script type="text/javascript">
$(document).ready(function() {
    $('#user').keyup(function() {
        var user = $(this).val();
        $.ajax({
            url: 'check_user.php',
            type: 'POST',
            data: {username:user},
            beforeSend: function(){
                $('#response').text('Wait.Checking Availablity');
            },
            success: function(response){
                $('#response').html(response);
                //alert(response);
              
    if(response == 'Not Available')
    {
  
        $("#user").removeClass("green");
         $("#user").addClass("red");
        msgbox.html(response);
    }
    else
    {
        $("#user").removeClass("red");
        $("#user").addClass("green");
        msgbox.html('<img src="available.png" align="absmiddle">');
    }
 

            }
        });
    });
});
</script>
Please share your comments and feedback.Thanks.

No comments:

Post a Comment