ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Check whether User Name already exists using JavaScript and XmlHttp
Author Name: Mudassar Khan Published Date: February 03, 2009
Filed Under :
C#.Net
 |
JavaScript
 |
AJAX
 |
VB.Net
Views: 8934

Many Websites use this to check asynchronously whether the username entered already exists and if it then display message to the user to choose a different username.

To start with you need a textbox where the username will be entered and a label to display the message.

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>

<asp:Label ID="lblMsg" Text = "UserExists" runat="server"

                style =" visibility:hidden "></asp:Label>


Now to make AJAX call to the server I will use XML HTTP.

To read more about XML HTTP you can refer here.

AJAX Calls Using JavaScript And XMLHTTP in ASP.Net

Sending the Request

The following function makes a asynchronous calls to the server.

<script type="text/javascript">

var xmlhttp;

function CheckUser(url)

{

    xmlhttp=null;

    if (window.XMLHttpRequest)

    {

        // code for all new browsers

        xmlhttp=new XMLHttpRequest();

    }

    else if (window.ActiveXObject)

    {

        // code for IE5 and IE6xmlhttp=

        new ActiveXObject("Microsoft.XMLHTTP");

    }

    if (xmlhttp!=null)

    {

        xmlhttp.onreadystatechange=state_Change;

        xmlhttp.open("GET",url,true);

        xmlhttp.send(null);

    }

    else

    {

        alert("Your browser does not support XMLHTTP.");

    }

 }</script>



Processing the Request

The request is received server side and you can check whether user exists and return the status as true or false.

C#

protected void Page_Load(object sender, EventArgs e)

{

    if (Request.QueryString["UserName"] != null)

    {

        String strUserName = Request.QueryString["UserName"];

        //Check userName Here

        String strReturnStatus = "false";

        if (CheckUsername(Request.QueryString["UserName"]) == true)

        {

            strReturnStatus = "true";

        }

        Response.Clear();

        Response.Write(strReturnStatus);

        Response.End();

    }

}



VB.Net


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Request.QueryString("UserName") Is Nothing Then

        Dim strUserName As String = Request.QueryString("UserName")

        'Check userName Here

        Dim strReturnStatus As String = "false"

        If CheckUsername(Request.QueryString("UserName")) = True Then

            strReturnStatus = "true"

        End If

        Response.Clear()

        Response.Write(strReturnStatus)

        Response.End()

    End If

End Sub


I am using a dummy function CheckUserName you’ll need to replace that with your function.



Receiving the Response

The following function receives the response from the server

true - Username Exists

OR

false -Username does not Exists



<script type="text/javascript">

function state_Change()

{

if (xmlhttp.readyState==4)

{// 4 = "loaded"

 

    if (xmlhttp.status==200)

    {// 200 = OK               

        // ...our code here...

        var lblMesg = document.getElementById("<%=lblMsg.ClientID%>");

        if(xmlhttp.responseText=="true")

        {

            lblMesg.style.visibility = "visible"; 

        }

        else

        {

            lblMesg.style.visibility = "hidden";

        }

    }

    else

    {

        alert("Problem retrieving XML data");

    }

}

}

</script>


The above code does a simple check that is if the Response is true then shows the label to the user else if it is false then hide the label.


You can call the JavaScript function to check username in different ways.

1.     Give a button and allow user to check it

2.     Call the function automatically when the textbox loses focus.


I will explain the second technique here

To the Page Load event add the onchange event Attribute.


C#

txtUserName.Attributes.Add("onchange",

"CheckUser('XMLHTTPCSharp.aspx?UserName=' + this.value)");



VB.Net

txtUserName.Attributes.Add("onchange",

"CheckUser('XMLHTTP.aspx?UserName=' + this.value)")



The Above code is tested in the following Browsers


1.     Internet Explorer 7

2.     Firefox 3

3.     Google Chrome



You can download the source code here.

CheckUserExists.zip (2.92 kb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code



 


Community News