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
  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 a new config.php file.

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

Create a new ajaxfile.php file.

Check $_POST['username'] value in users table. If username 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

Send AJAX request when keyup event trigger on username field where 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().trim();

      if(username != ''){

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

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

             }
         });
      }else{
         $("#uname_response").html("");
      }

    });

 });
</script>

6. Demo

View Demo


7. Conclusion

In this tutorial, I showed how you can check username is already taken by someone or not with AJAX.

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

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

13 thoughts on “Check Username Availability with jQuery and AJAX”

  1. Hello, thank you for this code, it works very well. Do you possibly have additional code that will enter the information into the user database? I tried adding the following PHP code to index.php but it did not work:
    if(isset($_POST[‘submit’])).
    { $sql = “INSERT INTO user (username, emailid, password).
    VALUES (‘”.$_POST[“username”].”‘,””.$_POST[“emailid”].”‘, ‘”.$_POST[“password”].””)”;
    $result = mysqli_query($conn,$sql); }

    Thank you very much.

    Reply

Leave a Comment