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.
Please specify what exactly the statement should be if I use JS callback method. I am getting error due to eval method.
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.
I get the same thing in IE. I copied the code from the demo page. Any ideas?
Change your database, you must have left it as (db) and not ($Database)
I really like this simple code, BUT i can´t get it to work as it should.
I´m trying to use the code with my database, (with existing users), but the script says “Sorry but username trwtwrtwrt is already taken.”.
I have tried many bogus usernames, and all seems to be “taken” regarding this script.
Daniel,
You need to check that your MySQL returns proper results and then accordingly populate the $available variable .. Since this message depends on simple if/else loop/
I know that. But it seems so work now, after i cleared the browser cache.
One other thing tho… how can i change it so i don´t have to press the submit button all the time? (mouseclick would be much better.)
hi… can u plz send me the code of vadition and events using ajax..plz send me as soon as possible b’coz i hve interve the day after tommorow…..
thanxs
I have no errors using this, but it keeps telling the username is available although its already registered.
$query = “Select * from USERS where username = ‘$user’ “;
This is correct, i have a username field and a table called USERS.
Also added these as you suggested:
$result = mysql_query($query);
$available = mysql_num_rows($result);
dunno whats wrong
Hi sachin, firstly thanks for your code its working without mysql,, and wen im try to do with mysql its not even trying to functionate… please help me out…..
here is my code..
mysql_connect(“localhost”,”root”,”kspl1234″);
mysql_select_db(“users”);
$user = strip_tags(trim($_REQUEST['username']));
$sql= mysql_query(“SELECT * FROM users where username=’”.$user.”‘ ” );
$num= mysql_num_rows($sql);
$row= mysql_fetch_array($sql);
if($sql)
{
echo “Not available”;
}
else
{
echo “Available”;
}
Hello Sachin,
I am going to try the above code which you have given. But I need lot of help in making a dynamic driven website in PHP and need lot and lots of help from you…. I hope you will help me as I go ahead with my work.
Thanks and Regards,
Jagannath G
Thanks for this code, works well, but some parts need to be changed, for instance, switching: echo json_encode(array(‘code’ => 0, ‘result’ => “Sorry but username $user is already taken.” with: echo json_encode(array(‘code’ => 1,
‘result’ => “Success,username $user is still available.” and VICE VERSA.
hi sachin
i want check availability code for number.
in my application i want unique id two times so first field i gave auto increment but other field also i want unique and it is a unique number can you give me the code for this and php code and javascript code and html code pls help me i am totally fresher in this field
i m not able to understand the whole code. cn u just give me how it functions in a general way
hi! can u please explain this part to me
echo json_encode(array(‘code’ => -1,
‘result’ => ‘Invalid username, please try again.’
));