Check If User Name Exists Using AJAX And C#

April 26, 2009 | By | 11 Comments

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:

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.

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.

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.

 

Download Source Code

 

Filed in: ASP.NET, Mono 2.0 | Tags: ,

Comments (11)

Links to this Post

  1. DotNetShoutout | April 26, 2009
  2. Pattern Inc » 5 Practical Ways Using Ajax | February 3, 2010
  3. 5 Practical Ways Using Ajax | M3 Printing | February 6, 2010
  1. Jonathan Holland

    I would suggest not using an ASPX page for your ajax callback handler and instead look at using a HTTPHandler. These are much lighter weight.

    Another neat trick is that you could also use a ASP.NET WebService and have it wire up the JS automatically. If you did this, you could call the C# method from your JS without having to write any code.

  2. I wanted to keep this post simple, that’s why I didn’t use web service. I didn’t think of using HTTPHandler instead of an ASPX page, that’s an interesting thing to try. Thanks Jonathan.

  3. John

    Why not use HttpHandler for server side checking..Use JQuery/JSON it will be very easy..
    Example:
    http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx

  4. Thanks for the post.
    The same implementation could be observed from here also: http://dotnetspidor.blogspot.com/2009/03/check-username-availability-using.html

  5. “if(usernames.Contains(newUsername)) ”
    Where Usernames an simply an array? Can one do that in C# i’m not seeing that method.

  6. I’ve taken the liberty of making it work.
    protected void Page_Load(object sender, EventArgs e)
    {
    string newUsername = Request.QueryString["q"];

    int found=0;

    for(int i=0;i<usernames.Length;i++){
    if(usernames[i].Equals(newUsername)){
    found=1;
    }
    }
    if (found==1)
    {
    literal1.Text = "User name exists";
    }
    else
    {
    literal1.Text = "OK";
    }

    }

  7. I am not deep into programing, but I like your blog and your helpful posts!

  8. Excellent post..Keep them coming :) Thanks for sharing.

Leave a Reply

Trackback URL | RSS Feed for This Entry