Live Username Availability Check in PHP, AJAX & jQuery

On 9/22/2016

Hi! Here I'm going to show you about live username availability check in php and jquery ajax. I don't have to mention how much Signup process means for a website and two main entity required for it is, username and password. Moreover this username should be unique and it's important to check if the username already exists in database or not at the time of registration. Performing this username availability check live would be smart and can be accomplished using php and jquery ajax request.

Live Username Availability Check in PHP & jQuery AJAX:

During user signup, we have to determine if the username entered is already been taken or not. So the idea is to let users type in the username and once they move on to the next field, we send AJAX request to a backend php script where it checks against the database if username is already present or not and returns appropriate result.

Also we have to keep the submit button under disabled state and make it active only when the chosen username is unique and not yet registered. Here goes the implementation for the live username availability check.

Create MySQL Database:

This is the mysql database we'd need for checking username availability.

CREATE DATABASE `db_demo`;
Use `db_demo`;

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;

INSERT INTO `tbl_users` (`id`, `username`, `email`) VALUES
(1, 'foxadmin', 'foxadmin@example.com'),
(2, 'george26', 'georgefoxus@gmail.com'),
(3, 'userjack', 'jack.jil@outlook.com');

HTML & jQuery AJAX Script:

This one is the user interface page. It contains an html form with two input fields for username & email-id and a submit button. The submit button would be kept disabled by default and activated only when the username entered by the user is available to take.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Live Check for Username Availability Using PHP & jQuery AJAX | Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container" style="margin-top: 20px;">
    <div class="row">
        <div class="col-xs-4 col-xs-offset-4">
            <form action="check_username.php" method="post">
                <legend>Check Username Availabilty:</legend>

                <div class="form-group">
                    <input type="text" id="username" placeholder="Enter username" class="form-control" />
                </div>
                <div id="msg" class="form-group"></div>
                <div class="form-group">
                    <input type="text" id="email" placeholder="Email ID" class="form-control" />
                </div>
                <div class="form-group">
                    <input type="submit" id="submit" value="submit" disabled class="btn btn-block btn-primary" />
                </div>
            </form>
        </div>
    </div>
</div>

<script src="js/jquery-1.10.2.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#username").blur(function(e) {
    var uname = $(this).val();
    if (uname == "")
    {
        $("#msg").html("");
        $("#submit").attr("disabled", true);
    }
    else
    {
        $("#msg").html("checking...");
        $.ajax({
            url: "check_username.php",
            data: {username: uname},
            type: "POST",
            success: function(data) {
                if(data > '0') {
                    $("#msg").html('<span class="text-danger">Username is already taken!</span>');
                    $("#submit").attr("disabled", true);
                } else {
                    $("#msg").html('<span class="text-success">Username is available!</span>');
                    $("#submit").attr("disabled", false);
                }
            }
        });
    }
});
});
</script>
</body>
</html>

As you can see above, we have used jQuery's ajax() function to send ajax request to backend. The 'url' param of this function is something similar to the form action attribute and contains the php filename where the HTTP request is to be sent. And the param 'data' contains the form data as json string and sent along with the request.

Then there's the 'success' function which gets executed when there is valid response. It gets the response from the php script and notifies user if username is taken or not.

PHP Script:

This script connects to the mysql database and fires a query to determine if there is any matching entry for the username and returns the result to the AJAX function.

check_username.php

<?php
// mysql connection
$host = "localhost";
$user = "username1";
$pass = "password1";
$db = "db_demo";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));

if (isset($_POST["username"]))
{
    $username = mysqli_real_escape_string($con, $_POST["username"]);
    $sql = "select username from tbl_users where username='$username'";
    $result = mysqli_query($con, $sql);
    echo mysqli_num_rows($result);
}
?>

That's it. We have everything in place. Now run index.html file and type something for username and shift focus from the field. This will trigger the ajax call and the script informs if username is available or not. If the username you have entered is not yet registered then you will see message like this. And the submit button would be enabled.

live-username-availability-check-in-php-jquery-ajax

On the other hand if username is already taken then error message is shown and the submit button continues to be in disabled state.

check-if-username-already-exists-in-php-ajax

In this demo I have used blur() method to trigger ajax call however you can use change() or keyup() - but please be aware this would increase server load. So your best bet is to set some timer and send ajax request only when certain amount of time elapsed after user stoped typing.

Also Read: Live Search Engine Script using PHP, MySQL & AJAX

Don't Miss: PHP and MySQL User Login and Registration Script

So that explains about live username availability check using php and jquery ajax. You can customize the above code to better suit your requirement.

2 comments:

Contact Form

Name

Email *

Message *