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.
HTML
12345
<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.
JQUERY
12345678910111213141516171819
<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.
PHP
12345678910111213141516171819202122
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
  • 48 Comments

    Add Comment
    • Themiya
      can I please get a code check username, email and password seperately using ajax
    • Aysha
      Thank you so mutch for sharing am using your code at my site code working well thanks
    • Rajesh
      This code is not working.Please help
      • Manuel Ruiz Rajesh
        Try this:
        1234567891011121314
        //Check for avaliable user name
        	var x_timer;
        	var check_user_name;
        	$(document).on(&#039;change&#039;, &#039;#username&#039;, function(){
        		var check_user_name = $(&#039;#username&#039;).val();
        		clearTimeout(x_timer);
        			x_timer = setTimeout(function(){
        				//check_username_ajax(check_user_name);
        				$(&quot;#user-result&quot;).html(&#039;&lt;img src=&quot;img/ajax-loader.gif&quot; /&gt;&#039;);
        				$.get(&#039;test.php&#039;, {&#039;usuario&#039;:check_user_name}, function(data) {
        					return $(&quot;#user-result&quot;).html(data);
        				});
        			}, 1000);
        	});
    • Alpesh Katariya
      Great one example good work for me
    • Dheeraj
      Hello, Would you be able to share the MySQL database you used in this demo?
    • Kabel mic
      good nice....
    • Aldrich Gat
      Its nnot working. i followed all the steps
    • Nathan
      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); });
      • San Nathan
        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.
        JQUERY
        1234567891011121314
        $("#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/
    • Mahendra sharma
      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.