-
Checking availability of user name with AJAX
Posted on March 5th, 2009 9 comments
Lately I’ve been writing quite much about AJAX, but it is so useful that I’m sure it is of everyone’s interest!
In this post I will show you – as the post title says – an example script of AJAXed registration form, without recurring to AJAX frameworks (there are already many tutorials about this topic in relation with them). The example omits the synchronous part of the registration and focuses on the user name, which we want to asynchronously check. It doesn’t sound so weird if I say it in other words: check on the fly if the user name the person is typing already exists in the database or not, and take actions depending on whether it does or not (for instance, only allow form submission if name is available).
This is the basis for other types of effects like for instance searching contents and dynamically returning result suggestions, or checking if a specific word exists in the database, etc. but as I mentioned, here the intention is to use it on a registration form.
First of all, check the demo of the script here.
Let me point out two things you might have noticed:
- Names of 3 or less characters are not checked.
- Names are checked only after finishing writing.
What’s the point for this? The answer is, filtering the queries.
The required number of characters is useful because most user registration forms ask the user for a longer name than just ‘abc’. It is also useful to filter out useless queries to the database for names which are not allowed because they’re too short.
Checking the names once the user finished writing is useful depending on the event which triggers the name check. In the example, the event is onkeyup and this would normally mean querying the server each time the user has typed a character (excessive!). By using this filter however, there must have been a certain time of inactivity for the script to fire; otherwise the user is considered to still be typing in and therefore there’s no need to query the server for every new character. Some events like onchange do not really need this filter.
Now let’s see the script in detail, for which two files are needed:
- index.html
- check.php
index.html
<script type="text/javascript"><!-- // Custom settings var minlength = '3'; // Set to minimum required characters as specified in your form var delay = '1000'; // Time of inactivity to check. Always in milliseconds! (1 sec = 1000 millisec.) var divid = 'username_exists'; // ID of the DIV where response will be shown // Wait for user to finish typing function timeoutUsernameCheck(){ if(window.mytimeout) window.clearTimeout(window.mytimeout); window.mytimeout = window.setTimeout("toggle_username()", delay); return true; } // Check availability function toggle_username() { if (window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http = new ActiveXObject("Microsoft.XMLHTTP"); } handle = document.getElementById('username'); var url = 'check.php?'; if(handle.value.length > minlength) { // Timestamp for preventing IE caching the GET request fetch_unix_timestamp = function() { return parseInt(new Date().getTime().toString().substring(0, 10)) } var timestamp = fetch_unix_timestamp(); var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value) + '&timestamp=' + timestamp; http.open("GET", fullurl, true); http.send(null); http.onreadystatechange = statechange_username; }else{ document.getElementById(divid).innerHTML = ''; } } // Show availability function statechange_username() { if (http.readyState == 4) { var html = http.responseText; document.getElementById(divid).innerHTML = html; } } // --></script> Is the username available? <div id="wrapper"> <div id="left" style="float: left; margin-right: 8px;"> <form> <label style="margin-right: 6px;" for="username">User name: </label> <input id="username" style="display: inline;" onkeyup="timeoutUsernameCheck()" name="username" size="20" type="text" /> </form></div> <div id="username_exists" style="display: inline; font-size: 11px; font-weight: bold; color:#FF3300"></div> </div>The function called by the event onkeyup of the input field is timeoutUsernameCheck(). This function is one of the two filters mentioned above; it checks whether the user finished typing the name or not before triggering the checking process. It is difficult to know, when the event is onkeyup, the exact moment a user finishes typing (easier to know for instance with events onchange and onblur, or making the user click a button to check). So what we do with this function is assume that the user finished writing if he is more than X seconds inactive at typing. A recommended value here is around 1 second (1000 milliseconds), but of course any value can be used; this value is suggested because normally people do not take so long to type in the next character. The smaller the value is, normally the more times the script will run and check the database for matching names, but also the faster the user will know whether the name is available or not. One must find the adequate balance for each site’s needs.
check.php
// Connect to MySQL DB mysql_connect ('localhost', 'user', 'pass'); mysql_select_db('dbname'); $do = $_GET['do']; switch($do) { case 'check_username_exists': if(!get_magic_quotes_gpc()) { $username = addslashes($_GET['username']); }else{ $username = $_GET['username']; } $count = mysql_num_rows(mysql_query("SELECT * FROM login WHERE username='".$username."'")); if($count > 0) { // User name not available echo '<img src="cross.jpg" alt="" width="22" height="22" />'; }else{ // User name available echo '<img src="check.jpg" alt="" width="22" height="22" />' } break; default: echo 'No action specified.'; break; } ?>There’s nothing special in this part of the code, it is a quite simple PHP script. First of all it connects to the MySQL database where the user names are recorded; then it checks what operation we want to do (check_username_exists), and if this is specified in the GET variables passed with the URL, the database is checked for matching names. Then it returns one of two possible responses: either name is available (no matching names) or it is not available (the name already exists in the database).
In the demo, the response is not textual but a small image: a green check mark indicates that the name is available, whereas a red cross indicates the name is already taken. Further actions can be coded.
Finally, I believe it is a good idea to check again whether the username is available or not when the registration is submitted. This is because in pages with very frequent registrations, a username might be taken by user Y while user X is still filling in the registration form after having received the message that the username he chose is available.
The images used for the demo can be found here:
Related posts:
AJAX, Computers & programming, HTML, JavaScript, MySQL, PHP ajax, asynchronous, available, check, code, database, div, form, get, html, javascript, login, mysql, php, refresh, registration, reload, retrieve, table, user, username, web 2.0, xml9 responses to “Checking availability of user name with AJAX”
-
thanks for script .
pla suggest me how to give link to the check availability instead of on key up click.
very urgent
-
Aleix April 2nd, 2009 at 13:00
In index.html:
1. Replace the input field code with this:
< *input id="username" type="text" name="username" size="20" style="display: inline;"/>
remove *
2. Add the availability check link anywhere in the page:
< *a href="javascript:void(0);" onclick="timeoutUsernameCheck()">Check< */a>
remove *
This will stop making automatic checks and will only perform them when user clicks on link.
3. Change delay to 0, replacing the existing var delay = ‘1000′; with:
var delay = ‘0000′;
That’s the quickest and easiest way, and works.
You may want to do further tweaks in the AJAX code to optimise it…Regards
-
Great tutorial I will be implementing this into my website.
I am wondering how would you add text box color such as green for success and red for an error?
Thank you
-
Hello,
Glad you will use it in your site! To change the input text box background color is luckily not complicated at all, as JS allows to dynamically change styles of DOM elements. Read more about it here: http://www.w3schools.com/Css/pr_background-color.asp
Here are the steps you need to take to get it to work:
in check.php
1. Replace line 20
for echo ‘0′;2. Replace line 25
for echo ‘1′;What this does is return a number instead of an image, depending on the result of the username availability check. 0 means submitted name is unavailable, while 1 means the opposite.
in index.php
3. Remove document.getElementById(divid).innerHTML = html;
4. After var html = http.responseText;
add if (html == 0) {
document.getElementById(’username’).style.backgroundColor=”#ff2c2c”;
} else {
document.getElementById(’username’).style.backgroundColor=”#ffffff”;
}Step 3 is to prevent the response number being showed to the user, as we only want to use it for telling JS whether to change colour or not. Step 4 is the snippet of code which actually changes the colour. You may replace the value with colour name, hex or RGB value.
If I forgot nothing, that should be all you need
Regards
-
Hey Aleix just wanted to say that I really appreciate you helping me out with that code snippet it worked great and saved me many hours of doing it on my own. I had a little trouble adding the text output via javascript but I finally got it and finished it.
You can check out the username availability function with the added text box color in the link below. The unavailable username is johnny.
http://www.sharperjafs.com/Account/Sign_Up.php
Is there anyway that I can donate some money to you because I would really like to show you thanks.
-
Hello Johnny,
I’ve checked your implementation, works nice! Just a quick tip: like a number of other users, I use NoScript Firefox plugin, which blocks JavaScript, and therefore unless I allow JS on the page, the username checker doesn’t work on default. To fix this you have the option to require JS; here you’ll find some ways to do so http://www.webproworld.com/discussion-forum/66271-how-do-i-require-javascript-active-scripting.html (namely, visitors may only register to your site if they have JS enabled).
About the donation: I thank you for your good intentions. I’ve implemented a donation button through PayPal at the sidebar for your convenience.
Regards
-
Yeah I realize that not everyone has JavaScript enabled in their browsers so I have both client side and server side validation. I think having any requirements that visitors must have to sign up will cause them to get annoyed so I try to create as much of a convenience I can for the visitor.
Thanks again man you really helped me out.
-
You need to change the “check.jpg” picture ..URL.
..
-
Fixed, thanks for pointing it out.
Leave a reply


