Validate Username Using jQuery AJAX, JSON, and ASP.NET Web Method

by aherrick 11. February 2009 08:59

As of late, I have been working on using AJAX in my code to call ASP.NET Web Methods and Web Services.  There are a couple of different ways to accomplish this, including using the ASP.NET Script Manager, (see here) however there is a lot of overhead with instancing the Script Manager that is not always necessary.

The method below using the jQuery.AJAX call which even includes built in error checking functionality.  In this example, I am going to call a Web Method in the code behind that will validate the username text field input and return a boolean regarding if the username is valid. 

In a normal production environment, in your Web Method you would want to hit a database to validate the input, however for this demo I am going to simulate that.  If the username entered equals “testuser”, the method will return false, otherwise return true resulting in a valid username.

First we are going to add our html to the page:

<div>
    Username:
    <input id="tbUsername" type="text" />
    <span id="valid"></span>
</div>
<!-- preload -->
<div style="display: none">
    <img src="images/available.gif" alt="available" />
    <img src="images/taken.gif" alt="taken" />
    <img src="images/waiting.gif" alt="waiting" />
</div>

Here I am creating a simple html textbox and span tag.  We will use the Javascript code to change the html of the span tag.  It is a place holder for now.  Also I add an image preload div using CSS so the necessary images are loaded at runtime.  display: none ensures the images will not be visible on the screen.  This ensures a smooth effect when hiding/showing the images dynamically.

Next we are going to create our simple Web Method in the code behind.

using System.Web.Services;
[WebMethod]
public static bool IsUserAvailable(string username)
{
    // simulating db call here
    if ((!username.Contains(" ") || !username.Contains("")) && username != "testuser")
        return true;
    else
        return false;
}
 
All we are doing is creating a simple method to return if the user is valid. 

Now lets take a look at the Javascript required to make this all happen.

<script type="text/javascript" src="scripts/jquery-1.2.6.min.js"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("#tbUsername").blur(function(event) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/IsUserAvailable",
                data: "{'username': '" + $('#tbUsername').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#valid').html("<img src='images/waiting.gif' alt='Checking username!'>");                       
                    var delay = function() {
                        AjaxSucceeded(msg);
                    };
 
                    setTimeout(delay, 2000);
                },
                error: AjaxFailed
            });
        });
    });
    function AjaxSucceeded(result) {
        if (result.d == true)
            $('#valid').html("<img src='images/available.gif' alt='Username available!'>");
        else
            $('#valid').html("<img src='images/taken.gif' alt='Username taken!'>");
    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }    
</script>

Here is where the magic happens.  Using jQuery we are getting a reference to tbUsername and adding blur event.  Adding the event through jQuery leads to better cross browser compatibility. 

Using jQuery.ajax we define our variables:

  1. type: “POST” – this ensures we are posting to the server
  2. url: “Default.aspx/IsUserAvailable” – sets the page and method we are calling
  3. contentType: “application/json; charset=utf-8”
  4. dataType: “json” – using JSON as the data type, this could be XML, etc.
  5. success: – here we are creating a function to determine what to do with the Response from the server i fit was successful
  6. error: – allows us to define an error method if something goes wrong.

Here is what our POST/RESPONSE looks like in debug mode with Firebug

POST:

usernamePost

You can see what we are sending, username defines the argument name and test is the value entered into the textbox.

RESPONSE:

usernameResponce

After successfully validating the username in the Web Method, it sends back a true.  For more information on what the d value is, give this blog post esconia a read.

Finally if the response was true, we set the html of the span to the success image, otherwise set it to taken!

I hope this code is a jump-off point to get you started with jQuery AJAX, JSON, and ASP.NET and gives you a glimpse at how powerful it can really be!  Posted below is the code in its entirely, please test it out and let me know what you think!

jQueryAJAXValidateUsernameWebMethod.zip (39.30 kb)

Tags:



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008