Live Username Availability using PHP & jQuery

In This Post,We will learn how to implement username live check availability feature using PHP, jQuery and MySQL.We will send AJAX request to server-side script(PHP) and get response from ajax request as a JSON object.We will show success/error message if the user name available/exists or validation type error.Its very useful when you are checking username availability on live form from database.

This functionality important when you are providing username availability on live enter of username.

live_Username_Availability

Step 1: Create table to store username into database.

Select Code
1
2
3
4
5
6
7
8
9
10
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO  `users` (  `id` ,  `username` ,  `email` ) 
VALUES (NULL ,  'phpflow',  'phpflow@phpflow.com'), 
(NULL ,  'parvez',  'parvez@phpflow.com')

Step 2: Created database connection file connection.php, to connect mysql to php.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

Step 3: Index.phpCreated layout file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
<form>
  <div class="form-group">
    <label for="exampleInputEmail1">User Name</label>
    <input type="text" class="form-control" name="username" id="username" placeholder="user Name">
    <span id="usercheck" class="help-block"></span>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

Step 4: Index.php
We will create java script method to get data from input box and validate with Ajax request, this method call on keyup event of input box. We are checking the username against the database on keyup we’re making a unique request each time.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#username').keyup(function() {
    var usercheck = $(this).val();
            $('#usercheck').html('<img src="loading.gif" width="150" />');
            $.post("check.php", {user_name: usercheck} , function(data)
            {
            if (data.status == true)
            {
            $('#usercheck').parent('div').removeClass('has-error').addClass('has-success');
            
            } else {
            $('#usercheck').parent('div').removeClass('has-success').addClass('has-error');
            }
            $('#usercheck').html(data.msg);
            },'json');
    });
});
</script>

Step 5: PHP Code – check.php
We will get Ajax request in this file send the appropriate message according request parameters.
If the user is entering valid username then we will display success message otherwise we will send error message.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
include_once("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
    {
        $response = array();
        $username = mysqli_real_escape_string($conn,$_POST['user_name']);
        $sql  = "select username from users where users.username='".$username."'";
        $res    = mysqli_query($conn, $sql);
        $count  = mysqli_num_rows($res);
        if($count > 0)
        {
            $response['status'] = false;
            $response['msg'] = 'Username already exists.';
        }
        else if(strlen($username) < 6 || strlen($username) > 15){
            $response['status'] = false;
            $response['msg'] = 'Username must be 6 to 15 characters';
        }
        else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
        {
            $response['status'] = false;
            $response['msg'] = 'Use alphanumeric characters only.';
        }
        else
        {
            $response['status'] = true;
            $response['msg'] = 'Username is available.';
        }
         echo json_encode($response);
    }?>

Live Demo & Download Code

  • ben

    Hi,

    This code looks good but where is the database connection?

    Thanks,

    Ben

    • Hi Ben,
      I had assumed , User has database connection layer.