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


Contents

  1. Table structure
  2. Database Configuration
  3. Create HTML layout
  4. Create PHP file to check username
  5. Validate and Send AJAX request using JavaScript
  6. Demo
  7. Conclusion

1. Table structure

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. Database Configuration

Create a config.php file.

Completed Code

<?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. Create HTML layout

Create a textbox to enter username and for displaying username availability status create a <div id="uname_response">.

Define keyup event on textbox that calls checkUsername(this.value); function.

Completed Code

<!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.

Check if username is POST or not. If POST then check $username exists in username field in the users table.

If exists then assign Username is Not Available to $response otherwise, assign Username is Available.

Return $response variable.

Completed Code

<?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

Create checkUsername() function that calls on keyup event triggers on the username textbox.

Check if username has a valid value or not. If not then display a warning message on <div id="uname_response" >.

If value is valid and the character length is greater than 4 then create XMLHttpRequest Class object to send AJAX POST request to ajaxfile.php file. Send username as data.

On successful callback replace <div id="uname_response" > content with responseText.

Completed Code

<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

You can use the same script to check email availability if in your project email is a unique field instead of a username.

Update the field name and value accordingly.

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

Leave a Comment