How to check Username Availability using JavaScript and PHP

When creating an online community, website, or social profile, it can be challenging to come up with a username that’s not already taken.

If the username is available, then the user can proceed with registration. If it isn’t, then the user must have to try again with a new username until they find one that is available.

This post will help you check username availability using JavaScript and PHP.

I am using the MySQL database in this tutorial.

How to check username availability using JavaScript and PHP


Table of Content

  1. Create a Table
  2. Database Configuration
  3. Username Availability Checker HTML Layout
  4. Create PHP file to check username
  5. Validate and Send AJAX request using JavaScript
  6. Demo
  7. Conclusion

1. Create a Table

I am using users table in the example. It has the following structure –

CREATE TABLE `users` (
   `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
   `username` varchar(70) NOT NULL,
   `fullname` varchar(80) NOT NULL,
   `password` varchar(80) NOT NULL
);

2. Create a Database connection file

Create a config.php file for database connection.

<?php

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

// Create connection
$con = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($con->connect_error) {
   die("Connection failed: " . $con->connect_error);
}

3. Username Availability Checker HTML Layout

Set up a text input field for entering a username, and create a <div id="uname_response"> element to display the availability status of the username.

Implement a keyup event listener on the text input field to trigger the checkUsername(this.value); function

<!doctype html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>How to check username availability using JavaScript and PHP</title>
</head>
<body>

   <div> 
       <input type="text" id="txt_username" name="txt_username" placeholder="Enter Username" maxlength='60' onkeyup="checkUsername(this.value);" />
       <!-- Response --> 
       <div id="uname_response" ></div> 
   </div>

</body>
</html>

4. Create PHP file to check username

Create ajaxfile.php file.

  1. Verify if a username has been submitted via the POST method.
  2. Check if the submitted username exists in the users table username field.
  3. If the username exists, assign the message 'Username is Not Available' to the $response variable; otherwise, assign 'Username is Available'.
  4. Finally, return the value of the $response variable.
<?php

include 'config.php';

// Read POST data
$data = json_decode(file_get_contents("php://input"));

if(isset($data->username)){
    $username = mysqli_real_escape_string($con,$data->username);

    $query = "select count(*) as cntUser from users where username='".$username."'";

    $result = mysqli_query($con,$query);
    $response = "<span style='color: green;'>Username is Available.</span>";
    if(mysqli_num_rows($result)){
         $row = mysqli_fetch_array($result);

         $count = $row['cntUser'];

         if($count > 0){
              $response = "<span style='color: red;'>Username is Not Available.</span>";
         }

    }
    echo $response;
}

5. Validate and Send AJAX request using JavaScript

Implement the checkUsername() function, which is triggered by the keyup event on the username textbox.

Verify whether the username has a valid value. If it doesn’t, display a warning message within the <div id="uname_response"> element.

If the username value is valid, and its character length exceeds 4 characters, create XMLHttpRequest Class object. This object is responsible for sending an AJAX POST request to the ajaxfile.php file, with the username as the request data.

Upon a successful callback, update the content of the <div id="uname_response"> element with the responseText.

<script>
function checkUsername(username){

   var usernameRegex = /^[a-zA-Z0-9]+$/;

   if(usernameRegex.test(username)){
       document.getElementById('uname_response').innerHTML ="";

       if(username.length > 4){

           // AJAX request
           var xhttp = new XMLHttpRequest();
           xhttp.open("POST", "ajaxfile.php", true); 
           xhttp.setRequestHeader("Content-Type", "application/json");
           xhttp.onreadystatechange = function() {
               if (this.readyState == 4 && this.status == 200) {

                   // Response
                   var response = this.responseText; 
                   document.getElementById('uname_response').innerHTML = response;
               }
           };
           var data = {username: username};
           xhttp.send(JSON.stringify(data));
       }
   }else{
       document.getElementById('uname_response').innerHTML = "<span style='color: red;'>Please enter valid value</span>";
   }

}

</script>

6. Demo

View Demo


7. Conclusion

If your project considers email as a unique field rather than a username, you can use the same script to check email availability.

Simply adjust the field name and corresponding value as needed.

If you found this tutorial helpful then don't forget to share.

Leave a Comment