So you are creating a signup form and you want to create a fancy looking username validation Ajax script. I know that looks fancy when you signup for Gmail or Yahoo mailbox, instead these kind of validation are now on every signup form.
We are going to create this simple script using Javascript, Ajax, and of course PHP for the server interaction. In this PHP script I have not shown how you can validate it using mysql, since that is not the motive of this article. So all you have to do is implement the MYSQL logic so that it returns you proper result of the username availability. I am using a boolean variable called $available in PHP script. You can turn it ON & OFF (using true and false) to test the working of complete script. Demo of this script can be checked on this Demo Page.
The server side logic for the username availability (validate.php)
<?php $user = strip_tags(trim($_REQUEST['username'])); if(strlen($user) <= 0) { echo json_encode(array('code' => -1, 'result' => 'Invalid username, please try again.' )); die; } // Query database to check if the username is available $query = "Select * from USERS where username = '$user' "; // Execute the above query using your own script and if it return you the // result (row) we should return negative, else a success message. $available = true; if($available) { echo json_encode(array('code' => 1, 'result' => "Success,username $user is still available" )); die; } else { echo json_encode(array('code' => 0, 'result' => "Sorry but username $user is already taken." )); die; } die; ?>
The HTML and ajax code.(validate.html)
<script type="text/javascript"> //function to create ajax object function pullAjax(){ var a; try{ a=new XMLHttpRequest() } catch(b) { try { a=new ActiveXObject("Msxml2.XMLHTTP") }catch(b) { try { a=new ActiveXObject("Microsoft.XMLHTTP") } catch(b) { alert("Your browser broke!");return false } } } return a; } function validate() { site_root = ''; var x = document.getElementById('uname'); var msg = document.getElementById('msg'); user = x.value; code = ''; message = ''; obj=pullAjax(); obj.onreadystatechange=function() { if(obj.readyState==4) { eval("result = "+obj.responseText); code = result['code']; message = result['result']; if(code <=0) { x.style.border = "1px solid red"; msg.style.color = "red"; } else { x.style.border = "1px solid #000"; msg.style.color = "green"; } msg.innerHTML = message; } } obj.open("GET",site_root+"validate.php?username="+user,true); obj.send(null); } </script> <style> #uname{border: 1px solid #000;} </style> <input type="text" id="uname" name="uname" value="" /> <input type="button" onclick="validate();" value="Check Availability" /> <div id="msg"></div>
How to make it work
It is very simple to make this script work. You need two files, a HTML file (say, validate.html) and a PHP file (say, validate.php) to interact with the database and check for the availability of the required username. Keep both files in same folder for making it to work correctly, otherwise if you want to keep the PHP file somewhere else, then you can specify the absolute path using the “site_root” variable defined in Javascript. You can also keep the Javascript code in separate JS file to keep the code clean. The most important thing is to keep the id names of the HTML elements same as the ones you are going to use in the JS code.
So now you have your own Signup form with bells & whistles. Hope this code helps you. Some may not be comfortable in using eval in the Javascript code, you can deal with JSON the way you like to.
Stay Digified !!
Sachin Khosla




Hello,
sorry my english is not so good.
I have a problem with this script. I will check the usernames from a mysql database.
How can i read the usernames from the database?
Pls help me
Janine
Hey Janine,
The mysql query depends upon your database structure, i.e. table name and the column names. The simplest query would be,
$query = “Select * from USER_TABLE where username = ‘$user’”;
You need to replace
USER_TABLE with the table name in whcih users are stored.
username with the actual column name you have in your table.
If you still have any problem, feel free to ask.
Thanks
Sachin Khosla
Hello Sachin,
it doesn’t work. I post my code here.
<?php
$DatabaseHost = "localhost";
$DatabaseUser = "xxx";
$DatabasePassword = "xxx";
$Database = "db";
mysql_connect($DatabaseHost, $DatabaseUser, $DatabasePassword) or die(mysql_error());
mysql_select_db(db);
$user = strip_tags(trim($_REQUEST['username']));
if(strlen($user) -1,
‘result’ => ‘Invalid username, please try again.’
));
die;
}
$query = “SELECT * FROM userdata WHERE Nickname = ‘$user’ “;
$available = true;
if($available)
{
echo json_encode(array(‘code’ => 1,
‘result’ => “Success,username $user is still available.”
));
die;
}
else
{
echo json_encode(array(‘code’ => 0,
‘result’ => “Sorry but username $user is already taken.”
));
die;
}
die;
?>
When i validate the nickname ever come Success,username xxx is still available
Whats wrong?
Pls help me.
Thanks
Janine
I see,
What you are missing here is, mysql_query
So in the above code,
REMOVE – $available = true;
and
ADD the following two lines
$result = mysql_query($query);
$available = mysql_num_rows($result);
That should solve your problem.
Thanks
Sachin Khosla
I Advance,
Please remove– $available = true;
and
use the following lines
$result = mysql_query($query);
$rows= mysql_num_rows($result);
then fixed your problem (Error).
Thanks & Regards.
Sava Intl.
Hi Sachin,
thx for the code it really helps.
however in your code, we gotta click on the “check availability” button first to validate the username right? what if i want to validate the username without even clicking the button?
so for example: i have 2 inputs, username and password. in this case i type “rocky” into the username box, and when i click my mouse on the password box (onchange), the website will alert whether the username is available or not. How can i achieve that?
Thank you.
Regards
Rocky
Rocky,
This is fairly simple to do. You can remove the button and instead associate the JavaScript function onblur event of input text, instead of onclick for the button.
Hi, very helpful info thanks.
I wonder if you could elaborate on this: “Some may not be comfortable in using eval in the Javascript code, you can deal with JSON the way you like to.”
Eg. What exactly does the eval part do and where can I go to find alternatives?
you can use a JS callback method instead, which takes JSON output as an argument.
Hi,
Great and simple script, thanks!
I’ve wrapped this up in a form with a submit button. Without clicking the availability button and clicking submit everything works fine. If I click the availability button, the script works, but if I follow this with my submit button a get a blank screen with {“code”:-1,”result”:”Invalid username”}.
It’s as if it’s calling my onclick event, any ideas?
Cheers.
just put onclick = “return false;” in case of submit buttons. It will stop the page to shift to the next action page.
Brent,
Check the ‘action=’ bit in your form declaration. Sounds to me (just a guess) that you have something like
You should be pointing it somewhere else, like maybe action=”join.php”
-James.
My HTML got stripped out. I’ll try posting again… sounds like you have something like:
<form action=”validate.php”> but validate.php is just for the ajax.
Cheers guys for the replies!
It turns out James it was that the file that ‘action’ was pointing to, it used a session ‘lastUrl’ which in some instances was ‘checkUsername.php’! When the form failed any field validation it redirected to this – hence the blank screen.
Nice one, thanks, great script Sachin!
Hi..
I am getting an error message saying missing “;” in firebug before
code = result['code'];
Can anyone help me. thanks.
be sure that you have correct JS code in your script. If you have any doubts goto the demo page and copy the javascript code from the page source, since that works fine.