29 May 2009

Getting to Grips with Form Submission using jQuery .ajax()

It surprised me a bit that with all the blog posts, tutorials, StackOverflow questions and other such resources, there was a scarcity of consolidated items available on how to do a simple AJAX post of some form values using an ASP.Net Web Method.  There are plenty of PHP articles, but .Net ones seem to be a little harder to come by (at least when I was looking this week).

I’m going to describe how jQuery’s .ajax() method works when you’re trying to retrieve a series of values from a form (a contact form in our example) and post those values to a Web Method on an ASP.Net page using JSON.

Step 1 : Lay Down the Foundations

I’m going to assume you have your own sample web page (if not, grab something from OpenDesigns.org or similar), but I’ll be using the follow HTML as my example:

Send us a message
Send Message

You’re also going to need jQuery (obviously).  I’ll wait here while you download it if you haven’t got any handy.

Finally, I’ll need an ASP.Net page that will be taking care of the postbacks.  I’m calling mine “contact.aspx”.

Step 2 : Coding the Web Method

Dave Ward has written an excellent article on how to use jQuery to directly call ASP.Net page methods and there’s no sense in reinventing the wheel here.  I’m going to elaborate on a couple of points from his article to look at handling some basic parameters: something that a JSON string can be very particular about.

My web method is going to look like this:

public partial class contact : System.Web.UI.Page
{
    [WebMethod]
    public static string SendMail(string Sender, string SenderEmail, string Message, string Subject)
    {
        string result = "";

        if (sendMessage(Sender, SenderEmail, Message, Subject))
        {
            result = "The mail must get through!";
        }
        else
        {
            result = "Epic Fail - postie eaten by neighbourhood dog.";
        }

        return result;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Ok, we have a very basic web method ready to go.  Next is the jQuery ajax call.  I’m going to start out with a more simple (i.e. inelegant) example.

        $(function() {
            $("#mySubmitButton").click(function() {
                // Set up a string to hold our JSON parameters.
                var dataString = "{'Sender': '" + $('#txtName').val() + "', 'SenderEmail': '" + $('#txtEmail').val() + "', 'Message': '" + $('#txtMessage').val() + "', 'Subject': '" + $('#ddlSubject').val() + "'}";

                $.ajax({
                    type: "POST",
                    url: "contact.aspx/SendMail",
                    data: dataString,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        $('#result-message').html(msg);
                    },
                    error: function(msg) {
                        $('#result-message').html(msg);
                    }

                });
            });
        });

Right. What have we accomplished here?  I’ll break it down piece by piece:

First, we tell jQuery to listen out for the click event for the “#mySubmitButton” element (this might be a button, link or even a paragraph tag if you want).  When clicked, we’re going to execute a function.

// Set up a string to hold our JSON parameters.
var dataString = "{'Sender': '" + $('#txtName').val() + "', 'SenderEmail': '" + $('#txtEmail').val() + "', 'Message': '" + $('#txtMessage').val() + "', 'Subject': '" + $('#ddlSubject').val() + "'}";

There’s nothing too complex going on here. All we’re doing is creating a string and grabbing the values from the controls that we want to pass to the web method. The tricky bit is getting all the single and double quotes right.

I should point out at this point that there are much better, cleaner ways to achieve this same thing.  However, for the sake of transparency and ease-of-understanding, we’re making the data string very verbose.

The next part is the actual AJAX command:

$.ajax({...

Let’s go through line-by-line and look at what each segment does:

type: "POST"

The “type” argument sets the type of request to make.  This would normally be “GET” or “POST”.  Get is the default.

url: "contact.aspx/SendMail"

This should be fairly obvious.  It’s the page and method name for the AJAX call.

data: dataString

This is our JSON data string (as described above).

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

The content type describes the type of data that is being sent to the server. A loose definition would be the data format description so that jQuery can parse the content correctly. I believe that Internet Explorer struggles with this part sometimes. It may be that you need to remove the charset declaration so that you’re only left with “application/json”. I’ve yet to confirm this and find out why it happens.

dataType: "json"

The data type tells jQuery what sort of data it can expect back as a response. This will be XML, HTTP, JSON (as in our case) or a number of other possible results.

success: function(msg) {
                        $('#result-message').html(msg.d);
                    },
                    error: function(msg) {
                        $('#result-message').html(msg.d);
                    }

This section deals with what to do once we get a response back from the server. There are a number of possible actions to take, but the two most common are “success” and “error” are the one’s we’re working with here. In each case, we define a function that describes what to do. In the event of success, we update the HTML in our “result-message” element with the response from the server. If we fail, we populate it with the returned error message.

That’s all that’s needed for a basic web method call. As I said at the outset, this is a simplified approach and once you get your head around the basics, there are more refined ways to achieve the same goals.

Other Reading

I recommend having a look at these other resources. The first one in particular.
Encosia.com : Using jQuery to directly call ASP.Net AJAX page methods

Opgenorth.net : ASP.Net Web Services and jQuery/AJAX

CodingDigest.com : Using jQuery in ASP.Net AJAX Applications (part 2)

Tags: , , , ,

One Response to “Getting to Grips with Form Submission using jQuery .ajax()”

  1. CustomPHP says:

    Very useful info. I learned a lot:) Thanks phil.

Leave a Reply

Real Time Web Analytics