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 the 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. CSS
  5. PHP
  6. jQuery
  7. Demo
  8. 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

Creating a <div id='div_reg'> which containing Registration form fields.

With username input field also created a <div id='uname_response' class='response'> for showing a message on the screen.

Completed Code

<div class="container">

    <div id="div_reg">
        <h1>Registration</h1>

        <div>
            <input type="text" class="textbox" id="txt_name" name="txt_name" placeholder="Name"/>
        </div>

        <!-- Username -->
        <div>
            <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username"  />
            <div id="uname_response" class="response"></div>
        </div>

        <div>
            <input type="password" class="textbox" id="txt_pwd" name="txt_pwd" placeholder="Password"/>
        </div>

        <div>
            <input type="password" class="textbox" id="txt_repwd" name="txt_repwd" placeholder="Re-type Password"/>
        </div>

        <div>
            <input type="submit" value="Submit" name="but_submit" id="but_submit" />
        </div>

    </div>

</div>

4. CSS

/* Container */
.container{
    margin: 0 auto;
    width: 70%;
}

/* Registration */
#div_reg{
    border: 1px solid gray;
    border-radius: 3px;
    width: 470px;
    height: 370px;
    box-shadow: 0px 2px 2px 0px  gray;
    margin: 0 auto;
}

#div_reg h1{
    margin-top:0px;
    font-weight: normal;
    padding:10px;
    background-color:cornflowerblue;
    color:white;
    font-family:sans-serif;
}

#div_reg div{
    clear: both;
    margin-top: 10px;
    padding: 5px;
}

#div_reg .textbox{
    width: 96%;
    padding: 7px;
}

#div_reg input[type=submit]{
    padding: 7px;
    width: 100px;
    background-color: lightseagreen;
    border: 0px;
    color: white;
}

/* Response */
.response{
    padding: 6px;
    display: none;
}

.not-exists{
    color: green;
}

.exists{
    color: red;
}

5. PHP

Create a new uname_check.php file.

Check $_POST['uname'] value in user table and returning the number of rows.

Completed Code

<?php

include "config.php";

/* Get username */
$uname = $_POST['uname'];

/* Query */
$query = "select count(*) as cntUser from user where username='".$uname."'";

$result = mysqli_query($con,$query);

$row = mysqli_fetch_array($result);

$count = $row['cntUser'];

echo $count;

6. jQuery

Send AJAX request when keyup event trigger on username field where pass the input value as data.

On successful callback check, the response value is greater than 0 or not.

If it’s greater than 0 then show Username already in use message in <div id='uname_response'> otherwise display Available message.

Completed Code

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

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

      var uname = $("#txt_uname").val().trim();

      if(uname != ''){

         $("#uname_response").show();

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

                if(response > 0){
                    $("#uname_response").html("<span class='not-exists'>* Username Already in use.</span>");
                }else{
                    $("#uname_response").html("<span class='exists'>Available.</span>");
                }

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

    });

 });
</script>

7. Demo

Try to enter yssyogesh, bsonarika, sunil, vijay, anil in the username field.


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

Related Post

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  

3 Comments

  1. Ratul said:

    Thank you, the code got me through.

    October 10, 2017
    Reply
  2. Kima said:

    Thank you Great tutorial. Works like a charm and is simple to understand

    January 18, 2018
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *