Check username availability with jQuery and AJAX

If you 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 submitting 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. CSS
  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,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

It have following users –

id username name
1 yssyogesh Yogesh singh
2 sona Sonarika Bhadoria
3 vishal Vishal Sahu
4 sunil Sunil singh
5 vijay Vijay mourya
6 anil Anil singh
7 jiten jitendra singh

 

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 from here, checking $_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 on username field change event and passing its values as data.

On success check, the response value is greater than 0 or not. If it’s greater than 0 then showing Username already in use message in <div id='uname_response'> otherwise Available message.

Completed Code

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

        $("#txt_uname").change(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. Conclusion

In this tutorial, I showed how you can check username is already taken by someone or not with AJAX. You can either send AJAX request on other events e.g. keyup, keydown, etc instead of change.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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