Friday, December 10

Ajax Username Check

I don't know about you, but I love cool ajaxy stuff. A lot of times, it's really simple to add this to a form. All I'm doing is checking to see if the requested username is in use or not.

So first, the html is the simple part. Just give your input box and id and add a section after it to hold the results:
<input type="text" name="uname" id="uname"><span id="checkuname">
Then I make a little php file with the to check for the username.
$u = $_GET['u'];
require_once('db.php');
if($u <> ""){ //we don't want to display anything if the field is blank
$checkname = query("SELECT * FROM table WHERE username = '".$u."'");
if(num_rows($checkname) <> 0){
$desc = 'Already in use';
}else{
$desc = 'Ok to use!';
}
}
echo $desc;
I style $desc to be something nice looking, or use an image of a checkbox or something, depending on how the rest of the form looks.

So then in the scripts, I look in the uname id and display in the checkuname id.
$('#uname').keyup(function(){
$('checkuname').load('checkuser.php?u='+$(this).val(), function(response, status, xhr){
if(status == "error"){
var msg = "There was an error: ";
$('#checkuname').html(msg + xhr.status + " " + xhr.statusText);
}
});
});

2 comments:

Josh Weatherly said...

Better watch out for Bobby Tables with code like that!

http://xkcd.com/327/

tygrr said...

I guess I failed to mention my first line is really "$u = mysql_real_escape_string($_GET['u']);"

I was trying to make it db independent and assumed people escaped their own inputs. Silly me :)