Username live check using Ajax PHP

Live username checker for registration has become useful part of registration system. It allows visitor to check for availability of username before they can register on one’s site. This script however can also be used for other purpose, such as checking city name, baby name or other miscellaneous things. Today let’s learn how we can create this nifty little script that checks available username for registration using jQuery Ajax and PHP.

username-check-ajax

HTML

Let’s assume, below is our registration page, it contains username input field, and span HTML element with ID user-result to dump ajax results.

1
2
3
4
5
<div id="registration-form">
  <label for="username">Enter Username :
  <input name="username" type="text" id="username" maxlength="15"> <span id="user-result"></span>
  </label>
</div>

jQuery

The idea is to let user type a username and wait for him to stop typing, once the user stops typing we can make Ajax request to our PHP script, which connects to database and checks whether username is listed on the database.

As you can see in jQuery code below, it makes Ajax request to PHP page as soon as user stops typing, it is determined by the time elapsed after user stops typing, this way we make less Ajax requests.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
$(document).ready(function() {
    var x_timer;    
    $("#username").keyup(function (e){
        clearTimeout(x_timer);
        var user_name = $(this).val();
        x_timer = setTimeout(function(){
            check_username_ajax(user_name);
        }, 1000);
    });

function check_username_ajax(username){
    $("#user-result").html('<img src="ajax-loader.gif" />');
    $.post('username-checker.php', {'username':username}, function(data) {
      $("#user-result").html(data);
    });
}
});
</script>

PHP

Here’s PHP code that will connect to your database table and check whether the value actually exist or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if(isset($_POST["username"]))
{
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    }
    $mysqli = new mysqli('host' , 'sql_username', 'sql_pass', 'database');
    if ($mysqli->connect_error){
        die('Could not connect to database!');
    }
   
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
   
    $statement = $mysqli->prepare("SELECT username FROM user_list WHERE username=?");
    $statement->bind_param('s', $username);
    $statement->execute();
    $statement->bind_result($username);
    if($statement->fetch()){
        die('<img src="public/images/not-available.png" />');
    }else{
        die('<img src="public/images/available.png" />');
    }
}

Demo

1
  • Saran

  • Article written by Saran. Saran Chamling loves the web technology, and enjoys designing, exploring and writing about it @sanwebe.com. You can find him at Twitter, Google or Facebook.

42 Comments Add Comment

  • Hello,

    Would you be able to share the MySQL database you used in this demo?

     Reply
  • good nice….

     Reply
  • Its nnot working. i followed all the steps

     Reply
  • I tried using your code and it’s not working. Your clearing out the timer before it’s done. Then it never, does what’s in the timer. Am I missing something?

    $(document).ready(function() {
    var x_timer;
    $(“#username”).keyup(function (e){
    clearTimeout(x_timer);
    var user_name = $(this).val();
    x_timer = setTimeout(function(){
    check_username_ajax(user_name);
    }, 1000);
    });

     Reply
    • You are right, because we want to execute the function only when user stops typing, otherwise we keep resetting the timer for each key press occurrence.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      $("#username").keyup(function (e){ //key press

              clearTimeout(x_timer); //clear any previously set timer
             
              var user_name = $(this).val(); // get text value
             
              //each keypress will set this timer to execute code after 1 second
              //but will be canceled by clearTimeout() as soon as user starts typing
              //so the point is, this timer will only succeed if user stops typing.
              x_timer = setTimeout(function(){
                  check_username_ajax(user_name);
              }, 1000);
             
      });

      Just tested the code, it’s working just fine :
      https://jsfiddle.net/k99ju9av/1/

  • Great work saran.. i wan to know which plugin you are using fow code highlightning… i am using WP-GeSHi-Highlight for code highlightning.. but some times it run the code on on page instead of highlightning the code.
    I have also write a code for username live check on http://songlers.com/blog/username-availability-code-using-ajax-php-mysql/

    But when i insert javascript code into the page it runs . kindly suggest a wordpress plugin.

     Reply
  • Great work. Been looking for something that realy works and Your script works for me. Simple and perfect at the same time.

     Reply
  • Why not use focusout() or blur() to check when the user leaves the field?

     Reply
  • Help me to provide search field to show particular record in the database. There is one solution but it shows username is available or not?

     Reply
  • Thanks for the code :)

     Reply
  • If you are not include jquery.js, those scripts will not work.

     Reply
  • the code won’t work if the data from auto select text box!!!!!!!

     Reply
  • it seems this code only work if the every single letter is type in. if the text box has already remember you user name, it does not work. for example, I used “Alex” as a user name in other web site, then google chrome can remember this, and when I want to register in this code, when I type a “A”, then “Alex” will show up . and I select “Alex”, guess what, the image is a check!

     Reply
  • Thanks, keep up the great work.

     Reply
  • Code work! Thanks for share. But how check form disable submit with jquery?

     Reply
  • How can i enter full name with space???
    this code is not allow space.
    plz help me as soon as possible.
    thanks for read :)

     Reply
    • Emerson M. Paguia

      you can add php validation rules like preg_match and allow spaces on it like I did…

  • i will try it your information very use helpfull

     Reply
  • There is also a nice tutorial on username and email availability using Ajax on http://www.talkerscode.com

     Reply
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    $(document).ready(function() {
            $("#username").keyup(function (e) {

                    //removes spaces from username
                    $(this).val($(this).val().replace(/\s/g, ''));

                    var username = $(this).val();
                    if(username.length = 4){
                            $("#user-result").html('');
                            //call to server via http post
                            $.post('check_username.php', {'username':username}, function(data) {
                                    if (parseInt(data) == 1){
                                            $("#submit").attr("disabled", false);
                                            $("#user-result").html('');
                                    }else if (parseInt(data) == 0){
                                            $("#submit").attr("disabled", true);
                                            $("#user-result").html('');
                                    }
                            });
                    }
            });
    });
     Reply
  • hy how using “Username live check using Ajax PHP” if condition multiple form
    I have try like this but dosent work for me

     Reply
  • Thanks, and keep up the good work!

     Reply
  • how if condition checking in multiple input
    for example :
    for username :
    for($i=1;$i<=$line;$i++)
    {
    <input type="text" name="username ” >
    }

     Reply
  • //if value is more than 0, username is not available
    if($username_exist) {
    die(”);
    // I want to set a textbox readonly here!.. what should i do?..
    //Thank you
    }else{
    // and here the oposite.
    die(”);
    }

     Reply
  • proper not work………..

     Reply
  • How can i prevent the form from submitting,if username is not available??

     Reply
    • I would love to know how to disable submit button if username is already taken.
      Please let us know how this should be done.
      Thanks in advance.

    • To disable submit button. I got around to it like this: Changed the output of the php echo to 0 and 1.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      $(document).ready(function() {
          $("#username").keyup(function (e) {
         
              //removes spaces from username
              $(this).val($(this).val().replace(/\s/g, "));
             
              var username = $(this).val();
              if(username.length < 11){$("
      #user-result").html('Phone number is too Short');
              $("
      #join_button").attr("disabled", true);
              return;}
             
              if(username.length >= 11){
                  $("
      #user-result").html('');
                  $.post('checkusername.php', {'username':username}, function(data) {
                  if(data == '1'){
                  $("
      #join_button").attr("disabled", false);
                  $("
      #user-result").html('Available');
                  $('#username').css('border', '3px #2ecc71 solid');
             
                  }else{
                      $("
      #join_button").attr("disabled", true);
                      $("
      #user-result").html(' – Already Registered');
                      $('#username').css('border', '3px #c0392b solid');
                  }
                 
                  });
              }
          });
      });

      By the way Sanwebe, great script. You are amazing.

    • Can you please show me how your php code returns the 0 and 1?
      Ive tried with echo “1” and echo “0” but this doesnt work for me.
      My submit button stills works

      ===========================
      JS Script
      ===========================

      $(document).ready(function() {
      $(“#usuario”).keyup(function (e) {
      //removes spaces from username
      $(this).val($(this).val().replace(/\s/g, ”));

      var username = $(this).val();
      if(username.length = 4){
      $(“#user-result”).html(”);
      $.post(‘verificar.php’, {‘username’:username}, function(data) {
      if(data == ‘1’){
      $(“#submit”).attr(“disabled”, false);
      $(“#user-result”).html(”);
      }else{
      $(“#submit”).attr(“disabled”, true);
      $(“#user-result”).html(‘Usuario existente‘);
      }
      });
      }
      });
      });

      ====================================================
      PHP Code Part
      ====================================================
      <?php
      $db_username = 'xxxx';
      $db_password = 'xxxx';
      $db_name = 'juego';
      $db_host = 'localhost';
      //check we have username post var
      if(isset($_POST["username"])){
      //check if its ajax request, exit script if its not
      if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
      die();
      }
      //try connect to db
      $connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
      //trim and lowercase username
      $username = strtolower(trim($_POST["username"]));
      //sanitize username
      $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
      //check username in db
      $results = mysqli_query($connecDB,"SELECT usuario FROM usuario WHERE usuario='$username'");
      //return total count
      $username_exist = mysqli_num_rows($results); //total records
      //if value is more than 0, username is not available
      if($username_exist) {
      echo "0"; //die('Usuario existente‘);
      }else{
      echo “1”; //die(”);
      }
      //close db connection
      mysqli_close($connecDB);
      }
      ?>

    • HI Juan, this is what I have on my PHP code: Using this directly with the Javascript should give you that functionality. It disables the submit button while it checks Username existence. If username is available it enables submit button. Otherwise submit button remains disabled.

      The entire credit goes to Sanwebe’s creativity.

  • how to send input information to function in file class.php without every time create file php for get this data :)

     Reply
  • nice post, and keep up the good work!

     Reply
  • Also I did add the echo comments. Still not working..

     Reply
    • It is hard to tell without looking at whole page. Problem could be in jQuery code, may be its not making ajax requests.

    • i think
      it should b
      if ($username_exist >0 )
      {
      die(“username not available”)
      }

  • I have shown my login details by mistake in this post. How do it edit and remove it ?

     Reply
  • Below is my code which is not working

    Form
    Enter Username :
    [cce lang=”jquery”]
    $(“#username”).keyup(function (e) { //user types username on inputfiled
    var username = $(this).val(); //get the string typed by user
    $.post(‘check_username.php’, {‘username’:username}, function(data) { //make ajax call to check_username.php
    $(“#user-result”).html(data); //dump the data received from PHP page
    });
    });
    [/cce]
    check_username.php

    [cce lang=”php”]
    < ?php ###### db ########## $db_username = 'xxx'; $db_password = 'xxx'; $db_name = 'xxx'; $db_host = 'localhost'; ################ //check we have username post var if(isset($_POST["username"])) { //check if its an ajax request, exit if not if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { die('Sorry, wrongly requested');exit; } //try connect to db $connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database'); //trim and lowercase username $username = strtolower(trim($_POST["username"])); //sanitize username $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH); //check username in db $results = mysqli_query($connecDB,"SELECT id FROM users WHERE username='$username'"); //return total count $username_exist = mysqli_num_rows($results); //total records //if value is more than 0, username is not available if($username_exist) { die(''); }else{ die(''); } //close db connection mysqli_close($connecDB); } ?> [/cce] http://www.landshoppe.com

     Reply
    • Your check_username.php isn’t outputting anything.
      It should be something like this :

      1
      2
      3
      4
      5
      if($username_exist) {
              echo 'Not Available';
          }else{
              echo 'Available';
          }