Joe Joe - 6 months ago 10
PHP Question

check username availability via ajax

I want to check if username is available via ajax. I currently am using the following code:

HTML

<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>


JavaScript

<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>


and here is php

<?php
if(isset($_POST["username"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$mysqli = new mysqli('localhost' , 'root', 'juaid123', 'project2');
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('Username Not Available!');
}else{
die('Username Available!');
}
}
?>


Everything work perfectly and my code show message in real time, but problem is i don't want to show any message if username characters is less then 6 and only want to allow letters and number in input field, can you please help me how i can do this..
Thanks

Answer

You can just use the HTML pattern attribute on your input to limit only numbers and letters http://www.w3schools.com/tags/att_input_pattern.asp. [a-zA-Z0-9]

Then you can just put a validation in your post function:

$("#username").keyup(function (e){
    clearTimeout(x_timer);
    var user_name = $(this).val();
    if(user_name.length >= 6){  //Validate number of characters here
        x_timer = setTimeout(function(){
            check_username_ajax(user_name);
        }, 1000);
    }
}); 
Comments