Check and Validate Username Without Page Refresh

Photo of Mike Dalisay
Modified Wednesday, February 23, 2011
by - @ninjazhai
Hi there! Today we are going to do a code snippet that:

1. Checks if a username is available or not (in the database). 
2. If the username is available, the program will output “[your_username] is available!”
3. Then if it is not available, “Username already taken” will be printed. 
4. This code also has a simple validation that states whether the inputted username is too short or is empty. 

All those tasks will be performed via AJAX, so it is without page refresh. You can expand its validation though.


In this snippet we need a sample data from the database table and four (4) files which includes: config_open_db.php, index.php, check.php and the jQuery library file.

database – you could have this table structure and data:

  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)

-- Dumping data for table `users`

INSERT INTO `users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

config_open_db.php – this file is for database connection so that we’ll be able to load usernames from the database. You should have something like this: (Please supply the variables with YOUR settings.)

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'codeofaninja'; 

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname) or die ('Unable to select  database!');
index.php – this file makes our user interface for this tutorial. jQuery library is of course included in this file.

    <title>Username checker and validator</title>
    <script type = "text/javascript" src = "js/jQuery.js">
    <style type = "text/css">
<script type = "text/javascript">
    //this script will be triggered once the 
    //user type in the textbox 

    //when the document is ready, run the function
        //we use keyup so that everytime the 
        //user type in the keyboard, it'll check
        //the database and get results
        //however, you can change this to a button click
        //which is I think, more advisable. 
        //Sometimes, your server response is slow
        //but just for this demo, we'll use 'keyup' 
            //this will pass the form input
            $.post('check.php', { username: form.username.value },
            //then print the result

        <form name = 'form'>
            <input type = 'text' id = 'username_input' name = 'username' >
        <div id = "feedback">
            <!-- the result will be shown here -->
check.php – this file makes the request to the database, to check the inputted value.

//define posted value
$username = isset( $_POST['username'] ) ? mysql_real_escape_string( $_POST['username'] ) : "";

if($username == null){
    //if no user input
    echo "Please enter a username.";
}elseif(strlen( $username ) < 5){
    //if the input is less than 5 characters
    //we used 'strlen' function to count string characters
    echo "Username is too short.";
    //query the inputted value
    $sql = "select  * from users where username = '$username'";

    $rs = mysql_query( $sql );
    $num = mysql_num_rows( $rs );

    if($num == 1 ){ //if username found
        while($row = mysql_fetch_array( $rs )){
            $fn = $row['firstname'];
            $ln = $row['lastname'];
            echo "<div style='color: red; font-weight: bold;'>Username already taken.</div>";
    }else{ //if username not found
        echo "<span style='font-weight: bold;'>$username</span> is available!";
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.