Live jQuery Ajax Username Availability Check

In this post I will describe how to check user name availability asynchronously before sing up with jQuery Ajax. This technique is mostly used by web developers. Because it save users time to sign up an account and it can also help to prevent duplicate accounts.

Live Demo Download Source
Database Design
First we need create a table called users that contains users information, like userid, username, password and whatever you want
CREATE TABLE `users` (
  `id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT ,
  `username` varchar(16) NOT NULL UNIQUE,
  `password` varchar(16) NOT NULL ,
);

Database Configaration
To connecting and working with db, we needs do some configuration
/**
 * DB Configuration
 */
define('DB_HOST', 'localhost');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');
define('DB_PASS', 'root');
/**
 * Connect and select MySQL DB
 */
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL server! ') . mysql_error();
$db = mysql_select_db(DB_NAME) or die('Fail to select MySQL DB ') . mysql_error();

HTML Markup
Take a look at the html markup, we take a html form with a input filed named username, where users will enter there username. We also need to add a empty div with id named usernameCheck. This div is the place where will show notification.
<!doctype html>
<html lang="en">
<head>
  <title>Live jQuery Ajax Username Availability Check</title>
</head>
<body>
<form action="" method="post">
  <div id="usernameCheck"></div><!--show notification -->
  <div>
    <label><span>Username:</span>
      <input type="text" maxlenght="16" id="username" name="username">
    </label>
  </div>
</form>
</body>
</html>

CSS Styling
We need to do little bit styling to show alerts
#usernameCheck{
  display: block;
  width: 24px;
  height: 24px;
  padding: 0px;
  background-repeat: no-repeat;
  background-position: center center;
  float: right;
  margin: 5px;
}
.usernameLoading{
  background: url(gif.gif)
}
.usernameFail{
  background: url(no.png)
}
.usernamePassed{
  background: url(ok.png)
}

jQuery and JavaScript Part
In this JavaScript code we first needs to include jQuery library. I add a event named keyup. This event executes when users write on the input field. When user writes more than 3 character length this script will send a asynchronous request using jQuery.ajax method.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var usernameCheck = $('#usernameCheck');
  $('#username').on('keyup', function(){
    var username = $('#username').val();
    if (username.length >= 3) {
      $.ajax({
        type: 'POST',
        cache: 'false',
        data: {username: username}, // form data
        beforeSend: function() {
          // show loading image
          usernameCheck.attr('class', 'usernameLoading');
        },
        success: function(d) {
          if (d == 200) {
            // show ok image
            usernameCheck.attr('class', 'usernamePassed');
          }
          else if (d == 201) {
            // show fail image
            usernameCheck.attr('class', 'usernameFail');
          }
        }
      });
    };
  });
});
</script>

PHP Part
This PHP script will receive asynchronous request that sent by jQuery.ajax and it will query into database table. If it will find no error it will echo out 200 or if it will find any error it will echo out 201.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  include_once('config.php');

  if (!empty($_POST['username'])) {
    # prevent sql injection
    $username = mysql_real_escape_string($_POST['username']);
    # username between 3-16
    if (strlen($username) >= 3) {
      # query users table
      $query = mysql_query("SELECT id FROM users WHERE username = '{$username}'");
      if (mysql_num_rows($query) < 1) {
        echo 200; # username not exist in db
      } else {
        echo 201; # username already exist
      }
    } else {
      echo 201;
    }
  }
  mysql_close($link); 
  return; # stop execution
}

No comments:

Post a Comment

Go to top