Check username availability with JQuery and ASP.NET
A cool use for AJAX is to let users know if a particular username is available or not while they are filling out the registration form. In the previous article "Check username availability with MS AJAX" I covered how to accomplish this task with MS AJAX. With all the excitement about JQuery being bundled with .Net/Visual Studio I thought it a good idea to show how to check username availability with JQuery.
The first thing you need is to have a database of usernames that can be queried. For this article and demo, I query the SQL Server DB used on this site. The following WebMethod will query the DB and check if a username is available or not. If the username already exists it returns true (meaning not available) and returns false if available.
Public Shared Function CheckUserName(ByVal userName As String) As Boolean
If (Membership.GetUser(userName) IsNot Nothing) Then
Return True
Else : Return False
End If
End Function
To the webform a label html tag, asp:textbox, and a span need to be added to the page so that your html will resemble:
<asp:Content ID="Content1" ContentPlaceHolderID="Content" runat="server">
Username: <asp:TextBox ID="TextBox1" runat="server" /><span id="spanChecking"></span>
</asp:Content>
You'll need to download jquery.js from http://docs.jquery.com/Downloading_jQuery. The current version is 1.2.6. We'll use the following jQuery script make the AJAX call to the WebMethod.
<script type="text/javascript" >
var $j = jQuery.noConflict(); //set no conflict so you can use with MS AJAX.
$j(document).ready(function() {
// Make the AJAX call to the WebMethod when the textbox loses focus
$j("#<%=Textbox1.ClientID %>").blur(function() {
$j.ajax({
type: "POST",
url: "jquerysample.aspx/CheckUserName",
data: "{'userName':'" + $j("#<%=Textbox1.ClientID %>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(message) {
//Set the spanChecking text letting user know if the uname is available
if (message.d == true) {
$j("#spanChecking").css({ "color": "red", "font-weight": "bold", "font-size": "small",
"padding-left": "15px" });
$j("#spanChecking").text("Username unavailable")
}
else {
$j("#spanChecking").css({ "color": "green", "font-weight": "bold", "font-size": "small",
"padding-left": "15px" });
$j("#spanChecking").text("Username available")
}
},
error: function(errormessage) {
//you would not show the real error to the user - this is just to see if everything is working
$j("#spanChecking").text(errormessage.responseText);
}
});
});
});
</script>
I set the noConflict property of jQuery so that there will not be any issues/conflicts with MS AJAX which is used on this site. If you do not use any other lirbaries then you use the standard jQuery reference of $. A little server side scripting is injected into the jQuery to obtain the client side ID of the textbox; the AJAX call then triggers when the textbox loses focus e.g. blurs. Alternatively you could have used a plain jane input textbox.
The actual ajax call begins at "$j.ajax". A couple of points to make here. One is that the url parameter must be in the format:
PageName.aspx/MethodName
The second point is regardiing the passing of the data parameter. The data that will be passed by the AJAX call to the server is the desired username and to obtain this we use the following jQuery expression.
$j("#
<%=Textbox1.ClientID
%>").val()
MS AJAX/ASP.NET AJAX script services and page methods understand the parameters serialized as JSON strings. MS AJAX automagically parses out the data and uses it as arguments to the method you’ve called.
However, if you directly provide JSON data as the parameter for our $j.ajax call, jQuery will try to serialize the data instead of passing it to the webmethod. In our case the data would end up being sent in the form of userName: Showjumper for example. An error is thenreturned - Invalid JSON primitive. To rectify this issue, the data has to be passed to the jQuery AJAX call as a string. JQuery will then send the string to asp.net for parsing. In our AJAX call above the data parameter would then evaluate as (assuming you checked for the username Showjumper):
"{'userName':'Showjumper'}"
If the username exists (e.g. not available), the value true will be returned. We check for this value and display a more friendly message by changing the text of spanChecking. If the username does not already exist we let the user know that the username is available. Also jQuery's excellent CSS capabilities are used to style the message. The CSS properties are specified as name/value pairs.
The last bit is the error parameter. When testing this code i returned the error message and displayed it as the text of spanChecking so I could debug this example when working on the article.
You can see the live demo here.