Our Blog

A blog by InetSolution about programming, security, design and marketing for banks, credit unions and e-commerce.

Using Classic ASP and AJAX to Check Availability of a Username on User Registration Form

In this example, I’m showcasing how we can use ASP and AJAX to check for whether a username exists before a user completes a website registration form. When registering to join a community website, such as www.digg.com, users must typically choose a username or handle. Normally such usernames must be unique to the community, and because of this new users often run into the problem of choosing a name that is already in use. A couple common results occur on a typical registration form when a user submits his data:

  • The page reloads with a message indicating that the username is already in use, allowing him to choose another username and try again.
  • In some very bad cases, the page is refreshed, destroying everything the user input on the form requiring him to start over.

I’ll be adding a feature that allows the user to enter a username and check immediately if the username is available before submitting the entire form. Through the use of AJAX and ASP, we will update only a small section of the page rather than reloading the entire page.

The key to AJAX is asynchronous execution. You can call a function either synchronously (which most developers are familiar with and find intuitive) or asynchronously (usually counterintuitive). If you’ve ever done network programming, you’re likely familiar with asynchronous calls where a new thread is created and your function is executing in this new thread. The benefit of a synchronous call is that it doesn’t interfere with the main thread, in this case, the web browser. (To further illustrate the point, synchronous calls are made in the main thread, which normally isn’t a problem until it’s something that takes a long time, and then the user is left waiting, usually thinking his computer has locked up).

Since an asynchronous call runs in its own thread, the user is free to continuing working on the current page. When the call finishes, it will trigger an event that will execute a callback function. The callback function is the conduit by which you will access the result of the asynchronous call; this should be familiar ground if you’ve ever worked with asynchronous calls.

You’ll notice back at the beginning of this example that the ‘X’ in AJAX comes from XML. The result that the callback function obtains from the server is basically a string of information, any information. Most articles I've read about AJAX always show the return information as XML, but in reality it can return any information you need whether it’s XML, HTML, or a packed array of database information.

The final step in implementing AJAX is to actually do something with the information that you get in the callback function. Normally, you’ll be updating some element on the page with the new information. You could add new values to a list box, update static text on the site or refresh whole sections of the page, it’s really up to you.
In this example, we’ll be updating a <div> with some new text information that will let the user know whether the username he chose is available.

Example showing unavailable username response

Example showing available username response

The above two examples show the result of the user entering two different usernames. We only updated the feedback text (i.e., available or unavailable), the entire page did not refresh or change in any other way in the user’s browser. Even if tthe operation takes a long time (poor network speed, an intensive operation etc), the user is still free to continue filling out the rest of the form.

For this example, I’ll only be including the code elements relevant to the example images above.

Client - HTML
<form method="post" action="javascript:void(0);" name="form1">

<table cellspacing="0">


<th><label for="newuserid">Username:</label></th>

<td><input type="newuserid" name="newuserid" id="newuserid" size="20" onKeyUp="OnChangedUsername();"/></td>

<td><input id="btnCheckAvailability" type="button" disabled="disabled" value="Check
Availability" onClick="OnCheckAvailability();"></td>

<td><div id="Available"></div></td>




Here we’re just creating the HTML code to display the labels, input boxes and, most importantly, the button and the fact that it calls the JavaScript ‘OnCheckAvailability’ function when it’s clicked. The div at the end is the item we’ll be updating on the web page asynchronously.

Client - JavaScript

//If our user enters data in the username input, then we need to enable our button
function OnChangedUsername()
if(document.form1.newuserid.value == "")
document.form1.btnCheckAvailability.disabled = true;
document.form1.btnCheckAvailability.disabled = false;

function OnCheckAvailability()
oRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
oRequest = new ActiveXObject("Microsoft.XMLHTTP");

oRequest.open("POST", "AJAX.asp", true);
oRequest.onreadystatechange = UpdateCheckAvailability;

oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.send("strCmd=availability&strUsername=" + document.form1.newuserid.value);

function UpdateCheckAvailability()
if(oRequest.readyState == 4)
if(oRequest.status == 200)
document.getElementById("Available").innerHTML = oRequest.responseText;
document.getElementById("Available").innerHTML = "Asychronous Error";

The ‘OnCheckAvailability’ function is the function that is called when the user presses the ‘Check Availability’ button. This basically creates either an ‘XMLHttpRequest’ or ‘Microsoft.XMLHTTP’ ActiveX object. We check for each type because each one is for a specific browser, either Microsoft’s Internet Explorer browser or a Mozilla type browser (such as Firefox).

NOTE: We are not performing any validation to enforce username constraints, such as numeric or special character restrictions. In a production system, you should also perform this validation prior to checking availability.

Next we open the request to the server using a “GET” or “POST”. When posting the data you need to include a header as I have.

You also must register a callback function that the server can call when it finishes executing the code. If you don’t do this, you won’t be able to handle any returned data (this may be what you want, if you're just making an asynchronous call to update something in a database for example). In my case I want to callback and handle the result of my query.

Finally, the last step is to actually send your data to the server, using the send() function of the request object.

The ‘UpdateCheckAvailability’ is our callback function; we registered it above in the OnCheckAvailable function. This function gets called after the server call has completed and has returned. You’ll notice the use of ‘readyState’ and ‘status’ in the request object. The readyState property allows us to handle the callback in the various states, 4 is the state that indicates a successfully completed operation. The status property indicates a standard HTTP response:

  • 200 being a successful response
  • 500 would be an internal error
  • 404 would be that the resource was not found

It’s a good idea to create error checking as I have so you have some clue when something goes wrong; you could elaborate on this even more to create a very robust callback feature.

(As a side note, it may be useful to throw in some alert() calls before readState and state, to see the control flow of the asynchronous call. The server actually calls back a few times on a successful calls, incrementing the readyState from 1-4 in succession, allowing you to hook into the various states for more advanced processing).

After we’ve confirmed that the call was a success, we can then check the response from the server, this is obtained through the request object’s ‘responseText’ parameter. You could also obtain data through ‘responseXML’, if you’re returning XML data. All that’s left is to update our DIV ‘Available’ to whatever the server sent to us, and we’ve updated the page without refreshing everything!

The glue that hooks the two JavaScript functions together and actually makes the callback back to the ‘UpdateCheckAvailability’ function is server side AJAX code. In reality, the AJAX code can be any server-side processing language such as ASP, ASP.NET, PHP, Python, Servlets etc. I’m using ASP as my server-side language of choice.

I’ve create a file AJAX.asp, which will serve as my AJAX ‘server’. In it I handle information from the client, in my case I’m only using AJAX for one part of my page but nothing says I couldn’t add a ton of AJAX functionality to my page, providing a very similar experience as a desktop application to the user.

Server - ASP

dim objRS
dim strSQL

set objRS = server.CreateObject("ADODB.RecordSet")

' Form Variables
dim strCmd
dim strUsername

strCmd = trim(Request.Form("strCmd").Item)
strUsername = trim(Request.Form("strUsername").Item)

select case strCmd
case "availability"
objRS.Open strSQL,objSecureDb.conn,adOpenForwardOnly,adLockReadOnly,adCmdText
if objRS.EOF then
Response.Write("Username " + strUsername + " is available")
Response.Write("Username " + strUsername + " is unavailable")
end if
case else
Response.Write("Invalid command: " + strCmd)
end select

set objRS = Nothing

The AJAX server is very simple; it creates a database connection (not shown) and a record set and extracts the information passed to it from the web page. The information passed was a command to the server as well as the username the user entered. Then a simple SQL statement is executed to find out whether or not the entered username already exists in the database or not.

We then return using some simple HTML markup the result of the SQL query, using colors as a better indication to the user what the status of their request is.

In the event that a developer entered and incorrect command, we simply respond back that the command was invalid, a great exercise in developing code that helps you help yourself and others. If for some reason something was wrong with the script itself, you would receive an Internal Error HTTP response of 500.

When this script finishes it will return our data to the client, which will then invoke the callback function we hooked in earlier. At that point as explained above, our information will be returned back to the web page and ultimately update the DIV with the appropriate information.


This is by no means the most efficient way of incorporating an AJAX implementation. For something simple, this is a perfectly solid route to take and will be much better than refreshing the page. However, you’ll notice I completely return the HTML from the server, when an improved method might be to return a simple one character digit that could later be interpreted as true or false, leaving the duty of outputting the correct message up to the JavaScript callback function. This choice is really up to you though.

A usability feature was also made to the example, but left out of this example because it did not have to do with AJAX itself. This was the simple decision to make the ‘Check Availability’ button disabled when the page loads. When the user begins typing into the username textbox, activate the button. In addition, if the user were to remove the text from the control then the button should again deactivate. This completes the full validation process for the ‘Check Availability’ feature described in this example.

This is just a very simple example of what the AJAX methodology can do, however an entire sight could be AJAX enabled, providing the user with a consistent and seamless browsing experience, which might go so far as to blur the lines between a desktop application and a web application.

Final Note

AJAX seems to be a catchphrase in the web development community lately and it may be confusing to a newcomer what exactly AJAX is, hopefully you’ve gotten a good idea reading this example, but suffice it to say that AJAX is really just a technique or methodology for passing data between client and server that ultimately relies on asynchronous calls. Such a technique has existed for a long time in networked applications and real-time applications as used in robotics; AJAX is simply the coined acronym for asynchronous web programming.


A Hype-Free Introduction to Ajax

Other Recent Blog Posts

Find this useful?

Want to receive our monthly tip to make your website easier to use and safer? No spam, just good advice. Signup!


Blog RSS Feed

Request a Consultation

Let us help you accomplish big goals.

Help us prevent spam: