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.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
- 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.JQUERY
- 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.PHP
- 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" />');
}
}