Check Username Availability with PHP, jQuery, and AJAX

If you are allowing the user to registration on your site then you have to make sure that every user has a unique username.

In this tutorial, we have write simple code that Live check username already exists or not by using jQuery and Ajax.

Username Availability Check using jQuery and AJAX

Contents

Database table

We are using users table in this example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Configuration

Creating a config.php file for define database and other configuration.

<?php

session_start(); /* Session Start name */

$host = "localhost"; /* Database Host name */
$user = "root"; /* Database User */
$password = ""; /* Database Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection is established or not. if not then stop execution with Connection failed error
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

HTML

Create aindex.php file. In it Create an input field for entering username and triggers AJAX call on “onkeyup event” of this input.

Show availability response in created <div id='username_availability_response'>.

<div id="custom-form-box" class="col-md-12">
 <form id="" class="form" action="" method="post">
    <h3 class="text-center text-info">Live Username Availability Check </h3>
    <div class="form-group">
       <label for="username" class="text-info">Username:</label><br>
       <input type="text" name="username" id="txt_username" name="txt_username" class="form-control">
       <div id="username_availability_response"></div>                         
    </div>                       
  </form>
</div>
Live Username Availability Check

jQuery

Send the username entered by the user along with the request for a ajaxfile.php PHP page.

<script>
    $(document).ready(function(){
        $("#txt_username").keyup(function(){
            // Get user input and trim it.
            var username = $(this).val().trim();            
            if(username != ''){        
                $.ajax({
                    url: 'ajaxfile.php',// file path
                    type: 'post',// method
                    data: {username: username},// Data send in JSON form
                    success: function(response){                
                        $('#username_availability_response').html(response);   
                         }
                });
            }else{
                $("#username_availability_response").html("");
            }            
        });
    });
</script>

PHP

Create ajaxfile.php file.

First check $_POST['username'] request is set or not, if set then Check it’s value in users table.

If username exists then return Available. message otherwise return Username Not Available… message.

<?php
// include config file
include 'config.php';
if(isset($_POST['username']) && !empty($_POST['username'])){
    // Escapes special characters in a string for use in an SQL query.
    $username = mysqli_real_escape_string($con,$_POST['username']);
    $query = "select count(*) as userCount from users where username='".$username."'";    
    $result = mysqli_query($con,$query);   
    if(mysqli_num_rows($result)){
        $row = mysqli_fetch_array($result);    
        $count = $row['userCount'];     
        // Check user count. 
        if($count > 0){            
            $response = "<span style='color: red;'>Not Available.</span>";
        }else{             
            $response = "<span style='color: green;'>Available.</span>";   
        }       
    }    
    echo $response;
    die;
}

Demo

Conclusion

In this tutorial, we showed how you can check Username Availability with PHP, jQuery, and AJAX without refreshing a page.

One Comment

  1. It’s hard to find well-informed people on this topic, however, you seem like you know what you’re talking about! Thanks

    February 21, 2022
    Reply

Leave a Reply

Your email address will not be published.