Check Username Availability using Ajax & PHP

In this tutorial, you will learn to check username availability using ajax, PHP & MySQL. Using this functionality, users can easily check the entered username is available or not in real-time before the submit form.

The username availability feature is mostly provided in a registration form if the login can be done using a username or password. Even you have seen this feature on many websites & social media like Facebook, Twitter & youtube.

Therefore, If you also want to integrate username availability functionality into your website then you will have to follow all the given steps without skipping any single point.

Check Username Availability using Ajax

Live Check Username Availability in Ajax & PHP

To start coding for checking username availability, First of you have to create a table named users with a username column and insert some records into this table.

You can also use your own table that has a column with the name or username.

Table Name – users

CREATE TABLE `users` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `firstName` varchar(255) DEFAULT NULL,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
);

Also, insert the following username into the table

  • demo123
  • test1234

1. Connect SQL Database to PHP

First of all, connect SQL database to PHP with the help of the following code or in the phpMyAdmin.

File Name – database.php

<?php
$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus";
// Create connection
$conn = new mysqli($hostname, $username, $password,$databasename);
// Check connection
if ($conn->connect_error) {
    die("Unable to Connect database: " . $conn->connect_error);
}

?>

2. Create Username Input Field

Create a username input field with a required attribute id=”username”  to take user input and also create a div with attribute id=”usernameStatus” to show a warning message.

You must include the following jquery ajax CDN to run the custom code of ajax.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Also, include the following script link of the ajax-script.js file to run its code while users are typing something into the username input field

<script type="text/javascript" src="ajax-script.js"></script>

File Name – form.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<input type="text" placeholder="Username"  id="username">
<div id="usernameStatus"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="ajax-script.js"></script>
</body>
</html>

3. Check username availability using Ajax

Now, Create a custom function usernameAvailability(usernameInput)  with some line of ajax code. Where –

  • usernameInput – It as a parameter that accepts will accept the input field of the username
  • url: “php-script.php” – This will call the php-script.php file when ajax will be executed
  • method:”POST”, – username will be sent to the PHP file securely

File Name – ajax-script.js

function usernameAvailability(usernameInput){
        $.ajax({
         method:"POST",
         url: "php-script.php",
         data:{username:usernameInput},
         success: function(data){
           $('#usernameStatus').html(data);
         }
       });
 }

3. Validate username Input using jQuery

Now, You have to validate username input on the input event that will be executed while users are typing something into the input field. If the username is successfully validated then the ajax custom function usernameAvailability(usernameInput) will be called.

Validation Rule –

username must be –

  • required
  • between 5 to 20 characters
  • without any whitespaces

File Name – ajax-script.js

$(document).on('input','#username',function(e){

    let usernameInput = $('#username').val();
    let msg;
    if(usernameInput.length==0){
      msg="<span style='color:red'>Enter username</span>";
    }else if((/^$|\s+/).test(usernameInput))
    {
     msg="<span style='color:red'>username can't contain spaces</span>";
    }
    else if(usernameInput.length!=0 && (usernameInput.length <5 || usernameInput.length >20)){
      msg="<span style='color:red'>username must be between 5-20</span>";
    }else{
      usernameAvailability(usernameInput);
    }
    $('#usernameStatus').html(msg);
});

4. Fetch available username using PHP

So, before using it, you will have to understand the following points

php-script.php file is created with some line of PHP & MySQL code to fetch the available username and check it is available or already taken. This is called in ajax-script.js like url=”php-script.php” and It will be executed while getting the input value of username from the ajax request.

First of all, You should include database.php file

Then check values of username (that comes from ajax request ) using if-else condition. If It is set and not empty then call a custom function checkUsername($conn, $userName) that will return “username is available” or “username is taken” by matching user input value with the value of existing in the database.

File Name – php-script.php

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

if(!empty(isset($_POST['username'])) && isset($_POST['username'])){

   $usernameInput= $_POST['username'];
   checkUsername($conn, $usernameInput);
  
}


function checkUsername($conn, $usernameInput){

  $query = "SELECT username FROM users WHERE username='$usernameInput'";
  $result = $conn->query($query);
  if ($result->num_rows > 0) {
    echo "<span style='color:red'>This username is taken. Try another</span>";
  }else{
    echo "<span style='color:green'>This username is available</span>";
  }
}

5. Check yourself to enter a username

You can check username availability features to enter something into the input field. If the entered value is already existed in the database then you will get a warning message ” This username is taken. try another” otherwise you will get another warning message “This username is available