Live Username Availability Check using PHP and jQuery AJAX

In this tutorial, we will see a PHP script to implement username live check feature using AJAX, jQuery and MySQL. This is a common and popular feature in most of the websites available online.

While creating a user account, just after the user enters the username, an AJAX call will request the PHP page at the serverside to get the availability status of the username. The PHP page matches the user input against the database and returns the response-text based on the availability.

jquery-live-username-check

Live DemoDownload

Check Username Availability Form Interface

This form contains username input field and triggers AJAX call on blur event of this input. The loader icon is shown to the user until the availability status is returned to the user interface.

<div id="frmCheckUsername">
  <label>Check Username:</label>
  <input name="username" type="text" id="username" class="demoInputBox" onBlur="checkAvailability()"><span id="user-availability-status"></span>    
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

jQuery AJAX Handler to Request User Availability

This Javascript function uses jQuery.ajax to send the username entered by the user along with the request for a PHP page.

function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}

Match Username against Database using PHP

This PHP script is executed as a result of the jQuery AJAX call. It compares database and user data to check username. Based on the availability status it will respond to the AJAX call.

require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["username"])) {
$result = mysql_query("SELECT count(*) FROM users WHERE userName='" . $_POST["username"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) echo "<span class='status-not-available'> Username Not Available.</span>";
else echo "<span class='status-available'> Username Available.</span>";
}

Live DemoDownload

This jQuery code tutorial was published on October 11, 2014.

↑ Back to Top