Realtime Username Availability Check
Examples
Test out functionality by using the username: test@test.com

HTML Code

<form class="col-md-6 col-md-offset-3 col-sm-12 col-xs-12 pt-3" action="#" method="post">
<div class="form-group">
    <label>Username</label><span id="userResult"></span>
    <input id="username" class="form-control" type="text" name="username" placeholder="Username" required/>
</div>

<div class="form-group">
    <label>First Name</label>
    <input class="form-control" type="text" name="firstName" placeholder="First Name" required/>
</div>

<div class="form-group">
    <label>Last Name</label>
    <input class="form-control" type="text" name="lastName" placeholder="Last Name" required/>
</div>

<div class="form-group">
    <label>Email</label>
    <input class="form-control" type="email" name="email" placeholder="Email" required/>
</div>
<button class="btn loginBTN" id="submitBTN" disabled>INVITE</button>
</form>            

jQuery Code

$("#username").keyup(function (e) { //user types username on inputfiled
    var username = $(this).val(); //get the string typed by user
    $.post('checkUsername.php', {'username':username}, function(data) { //make ajax call to check_username.php
        $("#userResult").html(data); //dump the data received from PHP page
    });
});            

PHP Code

<?php

include '../config.php';

if(isset($_POST["username"]))
{

    //trim and lowercase username
    $username =  strtolower(trim($_POST["username"]));

    //sanitize username
    $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);

    //check username in db
    $sql = "select id
            from users
            where username='$username'";
    $results = $db->query($sql);

    //return total count
    $username_exist = $results->num_rows; //total records

    //if value is more than 0, username is not available
    if($username_exist) {
        echo '<i class="fa fa-times" style="color:red;margin-left:15px;margin-right:5px;"></i>Username Unavailable';
        echo "
            <script>
                $('#submitBTN').prop('disabled', true); //TO DISABLED
            </script>";
    }else{
        echo '<i class="fa fa-check" style="color:green;margin-left:15px;margin-right:5px;"></i>Username Available';
        echo "
            <script>
                $('#submitBTN').prop('disabled', false); //TO DISABLED
            </script>";
    }
}