We all have experienced the wrath of filling out lengthy online forms. we get frustrated when we fill out the complete form and as soon as we submit it returns with messages like “UserName has already been taken”. So, now we have to fill the username as well as the password since password fields are not maintained during postbacks. In this article we will learn how to use Ajax request to lookup the existing username.

Introduction:

We all have experienced the wrath of filling out lengthy online forms. we get frustrated when we fill out the complete form and as soon as we submit it returns with messages like “UserName has already been taken”. So, now we have to fill the username as well as the password since password fields are not maintained during postbacks. In this article we will learn how to use Ajax request to lookup the existing username.

Implementation:

This problem can be solved in multiple ways. One solution is to cut the form in small pieces so that it works like a wizard control. This will only allow the user to fill small portion of information at a given time. This will have a faster response than loading the complete detailed form.

Another way is to ajaxify the username search. This means we will search for the existing username as soon as the user starts typing the username. Let’s check out how this approach is implemented.

First let’s make a few controls that we will need in our application: 

Enter UserName: <input type="text" id="txtUserName" />   
    Password: <input type="password"  />
   
    <div id="display" style="width:100px; font-family:Georgia; padding:5px 5px 5px 5px; font-weight:bold; font-size:14px"></div>
   


The div element is used to display the message whether the username already exists or not.

Now, let’s check out the JQuery code:

<script language="javascript" type="text/javascript">

var userName = '';
var keyChar = '';

$(document).ready(function()
{
    $("#txtUserName").keydown(function(e)
    {
        //userName = $(this).val();       
               
        keyChar = String.fromCharCode(e.which);             
       
        if(e.which == 8)
        {
            userName = userName.substring(0,userName.length - 1);
        }       
        else
        {
            userName += keyChar; 
        }
       
       
        if(userName.length <= 6)
        {
            $("#display").text("username must be atleast 7 characters");
            $("#display").css("background-color","red");
        }
       
        else
        {
            $.ajax(
            {
                type:"POST",
               
url:"AjaxService.asmx/CheckUserNameAvailability",
                data:"{\"userName\":\"" + userName + "\"}",
                dataType:"json",
                contentType:"application/json",
                success: function(response)
                {
                    if(response.d == true)
                    {
                        $("#display").text("username is available");
                        $("#display").css("background-color","lightgreen");
                    }
                    else
                    {
                      $("#display").text("username is already taken");
                      $("#display").css("background-color","red");
                    }
                }
            });
        }
       
       
    });
});


</script>


As, you can see we are restricting the user to make an Ajax call unless the username is of the required length. In this case the required length is greater than 6 characters. Let’s give this implementation a try in Firefox.


The above screenshot shows that for each keypress that happens after the 6 characters an Ajax call is made. This can end in many useless Ajax calls. A good web application is the one that makes fewer requests.

Let’s move our Ajax calls in the blur event of the TextBox which will be triggered whenever the user loses the focus from the TextBox control.

<script language="javascript" type="text/javascript">

var userName = '';
var keyChar = '';

$(document).ready(function()
{
    $("#txtUserName").blur(function(e)
    {
        userName = $(this).val();       
       
        if(userName.length <= 6)
        {
            $("#display").text("username must be atleast 7 characters");
            $("#display").css("background-color","red");
        }
       
        else
        {
            $.ajax(
            {
                type:"POST",
               
url:"AjaxService.asmx/CheckUserNameAvailability",
                data:"{\"userName\":\"" + userName + "\"}",
                dataType:"json",
                contentType:"application/json",
                success: function(response)
                {
                    if(response.d == true)
                    {
                        $("#display").text("username is available");
                        $("#display").css("background-color","lightgreen");
                    }
                    else
                    {
                      $("#display").text("username is already taken");
                      $("#display").css("background-color","red");
                    }
                }
            });
        }
       
       
    });
});


</script>

Now, the call will only be made when the user leaves the focus from the TextBox. Check out the animation below:


 

The animation shows that the Ajax calls are only made when the user losses the focus from the TextBox control. This will result in much fewer calls and will increase the performance of the application.

Also, if you are interested check out the screencast on the same topic:

Checking UserName Availability Instantly Using JQuery and Ajax

[Download Sample]