Skip to main content

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
}

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin . It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.