Check Username Availability with jQuery and AJAX

If you are allowing the user to login with their username and password then you have to make sure that every user has a unique username.

When the user goes for registration on your site check username either after form submits or check it with AJAX while entering.

In this tutorial, I am using jQuery AJAX to check username is available or not.

Check Username Availability with jQuery and AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP – Check username
  5. jQuery
  6. Demo
  7. Conclusion

1. Table structure

I am using users table in the tutorial example.

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

2. Configuration

Create config.php file for database configuration.

Completed Code

<?php

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

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create an input field for entering username and to show the availability response created <div id='uname_response'>.

Completed Code

<div>
   <input type="text" id="txt_username" name="txt_username" placeholder="Enter Username" />
   <!-- Response -->
   <div id="uname_response" ></div>
</div>

4. PHP – Check username

Create ajaxfile.php file to handle AJAX requests.

Check $_POST['username'] value exists in the username field in users table. If it exists then return Available. message otherwise Not Available. message.

Completed Code

<?php
include "config.php";

if(isset($_POST['username'])){
   $username = mysqli_real_escape_string($con,$_POST['username']);

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

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

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

   echo $response;
   die;
}

5. jQuery

Define keyup event on #uname_response.

Validate username and send AJAX request to ajaxfile.php file. Pass the input value as data.

On a successful callback write the response in #uname_response.

Completed Code

<script>
$(document).ready(function(){

   $("#txt_username").keyup(function(){

      var username = $(this).val();
      var usernameRegex = /^[a-zA-Z0-9]+$/;

      if(usernameRegex.test(username) && username != ''){

         $.ajax({
            url: 'ajaxfile.php',
            type: 'post',
            data: {username: username},
            success: function(response){

                $('#uname_response').html(response);

             }
         });
      }else{
         $("#uname_response").html("<span style='color: red;'>Enter valid username</span>");
      }

    });

 });
</script>

6. Demo

View Demo


7. Conclusion

I use keyup event to send AJAX request to check value similarly you can trigger this on any other events – keydown, change, click.

You can view the PDO version of this tutorial here.

If you want to know how to check username using Javascript then you can view this tutorial.

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