ajax01

You could make sure the user name entered during the registration process of your website is unique before the submit button is clicked using AJAX and C#. To accomplish this create two aspx pages. The first (default.aspx in this example) is the registration page, and it contains a TextBox control with an onkeyup element that calls the updateOutput JavaScript function and a span tag to display the HTML returned by the XMLHttpRequest.send function. The second page (doajaxstuff.aspx) should only contain following tags:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="doajaxstuff.aspx.cs"
   Inherits="ManualAJAX.doajaxstuff" %>

<asp:literal runat="server" id="literal1" />

The html, title and body tags should be removed because the page contents will be added to the default.aspx page, which already has these tags. The C# code that checks if the user name exists is in the Page_Load event of doajaxstuff.aspx. It gets the user name from the query string and displays the result in a Literal control. To keep the example simple I returned "User name exists" or "OK", but this could be changed to return an img tag to show a red cross image or a green tick respectively.

string[] usernames = { "admin", "administrator", "user1","user2",
					 "guest1", "guest2"};
protected void Page_Load(object sender, EventArgs e)
{
	string newUsername = Request.QueryString["q"];

	if(usernames.Contains(newUsername))
	{
		literal1.Text = "User name exists";
	}
	else
	{
		literal1.Text = "OK";
	}
}

The JavaScript code below does the AJAX work. The updateOutput function checks first if the TextBox is empty, and exits if true. Then it creates an object called xmlHttp which is an XMLHttpRequest object or an ActiveXObject, depending on the user's browser. XMLHttpRequest is supported in browsers from Internet Explorer 6, Opera 7.60, Mozilla 1.0, Netscape 7, Safari 1.2 and Konqueror 3.2. If the user has Internet Explorer 5 an ActiveXObject will be created, which basically does the same job. If the xmlHttp object is created the variable url will be assigned a string containing the page to call plus the query string, which is the string entered by the user in usernameTextBox.

The onreadystatechange event handler is assigned the name of the function StateChanged. This event occurs five times: when the request is initialized, set up, sent, being processed and completed. You could check which stage the request is in using the readyState variable (0, 1, 2, 3 and 4 respectively.) The if statement checks for 4 which is set when the HTML is downloaded to xmlHttp.responseText. The if statement also makes sure that xmlHttp.status is 200, which means no error occurred. If both these conditions are true the contents of xmlHttp.responseText are displayed in the span tag.

The open method sets the parameters of the request and contains three parameters; the request method, the URL of the request and a Boolean parameter that specifies the request should be executed asynchronously or not. The first parameter could be "GET", "POST", "HEAD" or "PUT". The second parameter is the relative or full URL of the page to request. And the third parameter should be true so the page could be called asynchronously.

The send method executes the request. Because the open method's first parameter is "GET", send's parameter is null. If open's first parameter was "POST" it would be a string containing the request parameters.

<head runat="server">
    <title>Manual AJAX</title>

    <script language="javascript" type="text/javascript">
        var xmlHttp;
        
        function updateOutput(inputString)
        {   
            if(inputString.length == 0)
            {
                document.getElementById("output").innerHTML = "";
                return;
            }
            
            try
            {
                if(window.XMLHttpRequest)
                    xmlHttp = new XMLHttpRequest();
                else if (window.ActiveXObject)
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");            
                    
                if(!xmlHttp || xmlHttp == null)
                {
                    return;
                }
                
                var url="doajaxstuff.aspx?q=" + inputString;
                xmlHttp.onreadystatechange=StateChanged;
                xmlHttp.open("GET", url, true);
                xmlHttp.send(null);
            }
            catch(e)
            {
                document.getElementById("output").innerHTML = "An error occured";
            }           
        }
        
        function StateChanged()
        {
            if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
            {
                document.getElementById("output").innerHTML = xmlHttp.responseText;            
            }        
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        Enter Username:
        <asp:TextBox runat="server" ID="usernameTextBox" 
            onkeyup="updateOutput(this.value)" />
        <span id="output"></span>
    </div>
    </form>
</body>

For this example the C# code in the doajaxstuff.aspx page searches an array containing the user names. This could be changed to search through the users in the aspnetdb database using the Membership.GetUser static function. I should also mention that the user can ignore the result of this validation check and submit a name that exists. To prevent this, the same validation should be done in the Submit button's code.