:::: MENU ::::

Tuesday, February 24, 2009

It's a common problem: you have a registration form, but you want to prevent user names or other values from being used more than once. You need a user-friendly way to prevent duplicate values being submitted. This is where the simplicity of jQuery excels.

User names and passwords are normally stored within a database. Commonly, developers wait until the form has been submitted before they perform any duplicate checking. This means that the user has to wait for a postback to complete before being informed that the user name they chose is already in use, and that they need to choose another one. Ajax tidies this up by allowing asynchronous querying of databases.

This example shows a very simple form:

 

<form id="form1" runat="server"> 

<div id="register"> 

  <fieldset>

    <legend>Register</legend>

    <div class="row">

      <span class="label">User Name:</span>

      <asp:TextBox ID="UserName" runat="server"></asp:TextBox><span id="duplicate"></span>

    </div>

    <div class="row">

      <span class="label">Password:</span>

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

    </div>

    <div class="row">

      <span class="label">&nbsp;</span>

      <asp:Button ID="btnRegister" runat="server" Text="Register" />

    </div>

  </fieldset>

</div> 

</form> 

 

A web service will be used to house the method that checks the database for possible duplicates:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Script.Services;

using System.Data.SqlClient;

 

/// <summary>

/// Summary description for UserService

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[ScriptService]

public class UserService : WebService {

 

    public UserService () {

    }

 

    [WebMethod]

    public int CheckUser(string username)

    {

      string connect = @"Server=SERVER;Database=Database;Trusted_Connection=True;";

      string query = "SELECT COUNT(*) FROM Users WHERE UserName = @UserName";

      using(SqlConnection conn = new SqlConnection(connect))

      {

        using(SqlCommand cmd = new SqlCommand(query, conn))

        {

          cmd.Parameters.AddWithValue("UserName", username);

          conn.Open();

          return (int)cmd.ExecuteScalar();

        }

      }

    }

}

 

There's nothing clever about this code. One (Web) method - CheckUser() - accepts a string as an argument and then returns the number of rows in the database where that name is found. The [ScriptService] attribute is uncommented, so that the service is availabe to AJAX calls (not just ASP.NET AJAX, incidentally).

Now we'll look at the Javascript that uses jQuery to effect the call:

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> 

<script type="text/javascript"> 

  $(function() {

    $("#UserName").change(checkUser);

  });

 

  function checkUser() {

    $.ajax({

      type: "POST",

      url: "UserService.asmx/CheckUser",

      data: "{username: '" + $('#UserName').val() + "'}",

      contentType: "application/json; charset=utf-8",

      dataType: "json",

      success: function(response) {

        var retval = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

        $("#duplicate").empty();

        if (response.d != "0") {

          $("#duplicate").html('That user name has alrady been taken');

        }

      }

    });

  }

 

</script> 

 

The first <script> tag brings in the jQuery library from Google's public code repository. Then an event handler is added to the element with the ID of UserName, which is the TextBox waiting for the user to put their chosen User Name in. The handler is wired up to the TextBox's onchange event, and calls the checkUser() function. Then the checkUser() function is defined in code.

When the user has added some text to the TextBox and then moves their cursor away, the chenage event is fired, and an AJAX call is made to the web service. If the response is not 0, then the web method has foound at least one row that matches the user name that the user is attempting to submit. The <span> with the ID is "duplicate" is emptied of any messages resulting from previous attempts, and the message displayed to the user.

More