I'm trying to do a username availability check on my website, i.e during registration, it checks if a username is taken or still available. However when i execute i get no result at all,nothing happens. My code:
Registration page
*register.php: *
//this form posts to the same script.
//In this script, i insert the registration data into database, including the username
<form action="register_page.php" method="post">
<label>Username:
<input type="text" name="newusername" id="newusername" required/>
<span id="user-result"></span>
</label>
//other form entries
</form>
still in register.php; in the head tag i have the following jquery
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(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 < 2){$("#user-result").html('');return;}
if(username.length >= 3){
$("#user-result").html('Checking...');
$.post('check_username.php', {'username':username}, function(data) {
$("#user-result").html(data);
});
}
});
});
</script>
and then i have another php script were the check is performed
check_usename.php:
<?php
$username = "root";
$password = "root";
$database = "db";
$server = "localhost";
//check we have username post var
if(isset($_POST["newusername"]))
{
//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();
}
$db_handler = mysql_connect($server, $username, $password);
$db_found = mysql_select_db($database,$db_handler);
//trim and lowercase username
$username = strtolower(trim($_POST["newusername"]));
//sanitize username
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
//check username in db
$results = mysql_query("SELECT id FROM tbl_user WHERE username='$username'");
//return total count
$username_exist = mysql_num_rows($results); //total records
//if value is more than 0, username is not available
if($username_exist > 0) {
die('<span>Username is taken</span>');
}else{
die('<span>Username is available</span>');
}
//close db connection
mysql_close($db_handler);
}
?>
Thanks in advance.