I was perusing Nettuts.com without much fanfare and saw the post by Matt Vickers on checking the accessibility of a username with Mootools. I tend not to utilize Mootools so i supposed I’d reproduce the system utilizing jquery. The code debases dexterously if Javascript is handicapped, it is exhorted that you dependably check the username against the database once more, simply before you add any information to the database.
The Javascript
So to begin with we have our jquery on report primed capacity, inside this we have an occasion audience .keyup capacity which when triggered runs the capacity ‘username_check’.
Inside the “username_check” capacity we firstly appoint the variable “username” to the worth of the data field with the id #username.
We now run a couple of watches that the username data field isn’t unfilled and that its 4 or more characters long. Provided that all is well and the username variable is over 4 characters we can hurry up and make the ajax appeal.
Its worth noting that since were checking the username against the database on keyup we’re making a novel solicitation every time. To assist restrict these appeals we watch that the username is more than 4 characters preceding perfoming an ajax appeal.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
$(‘#username’).keyup(username_check);
});
function username_check(){
var username = $(‘#username’).val();
if(username == "" || username.length < 4){
$(‘#username’).css(‘border’, ‘3px #CCC solid’);
$(‘#tick’).hide();
}else{
jQuery.ajax({
type: "POST",
url: "check.php",
data: ‘username=’+ username,
cache: false,
success: function(response){
if(response == 1){
$(‘#username’).css(‘border’, ‘3px #C33 solid’);
$(‘#tick’).hide();
$(‘#cross’).fadeIn();
}else{
$(‘#username’).css(‘border’, ‘3px #090 solid’);
$(‘#cross’).hide();
$(‘#tick’).fadeIn();
}
}
});
}
}
</script>
Taking a gander at “check.php”
This is the code that checks the database to check whether the username exists or not. dbconnector.php is the database association class that i use in all my ventures and is in the download of the activity records.
The predominant thing we do is trim any white space and change over the string to lowercase. i’ve guaranteed that the usernames in the database are all lowercase. So the usernames aren’t case delicate when a client sorts one into the container.
<?php
include("dbConnector.php");
$connector = new DbConnector();
$username = trim(strtolower($_POST[‘username’]));
$username = mysql_escape_string($username);
$query = "SELECT username FROM usernameCheck WHERE username = ‘$username’ LIMIT 1";
$result = $connector->query($query);
$num = mysql_num_rows($result);
echo $num;
mysql_close();