Aug 17

Today marks the beginning of using JQuery for handling AJAX requests. This is going to be a short post and we’ll be talking about the load method. The load method is able to perform get or post requests to replace the contents of the elements contained in the wrapped set with the response returned from the server side. As you’ve probably guessed, this method will only be usable in certain (few!) scenarios, where you’ll be writing the returned contents directly into one or more HTML elements (in my opinion, returning HTML from the server is a bad practice and you should avoid it at all costs).

To illustrate the use of the load method, we’ll start by creating a new ASP.NET handler (which I’ll be appropriately calling DumbHandler) which returns the current server time:

public class DumbHandler : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "text/html";
String.Format("<p><span>{0}</span></p>", DateTime.Now)); } public bool IsReusable { get { return false; } } }

Now that we’ve got the handler, we can concentrate on the client code. The load method expects until three parameters:

  • the url of the “page” that will be requested;
  • an optional data parameter that might contain an anonymous object with name/value pairs (results in a post request) or a string of name/value pairs (means you’ll be using a get request);
  • an optional callback method which will be fired when the AJAX request ends and each of the wrapped elements is updated with the returned content. Notice that this will also be called when you get an error in the request.

With this info, lets get started and build our first client AJAX script:

<p id="main">This is a paragraph</p>
<p>This is another paragraph</p>
<input type="button" value="Replace content" id="bt" />
<script type="text/javascript">
    $(function() {
        $("input[type=button]").click(function() {
            var url = "DumbHandler.ashx";

The idea is simple: we handle the click event by performing a remote request through the load method. Since we’re only passing the url, this means that we’ll be performing a GET request and that the returned contents will be “written” inside our p#main paragraph.

Lets suppose that I need to pass additional info to the server. If we want the info to be sent through GET, then we need to pass that information through the data parameter as a string. Here’s how we’d do that:

$("input").click(function() {
    var url = "DumbHandler.ashx";
    $("#main").load(url, "user=Luis");

Really simple, right? Ok,but what if we needed to get that info form form fields? In that case,the serialize method is the way to go. To illustrate this method, let’s start by adding a form to our HTML page:

    <label for="name">Name:</label>
    <input type="text" name="name" />
    <br />
    <label for="age">Age:</label>
    <select name="age">
        <option value="1">10-20</option>
        <option value="2">21-30</option>
        <option value="3">31-40</option>
        <option value="4">41+</option>
    <br />
<p id="main">This is a paragraph</p>
<p>This is another paragraph</p>
<input type="button" value="Replace content" id="bt" />

And here’s the changes we need to make to get the serialized info from our form fields:

$("input").click(function() {
    var url = "DumbHandler.ashx";
    $("#main").load(url, $("form").serialize());

If you want, you can only load a subset of the returned HTML. To do that, you need to filter the returned HTML by using a special selector delimited by SPACE on the url string. To show how this works, lets update our handler so that it returns the info that is sent through the AJAX request:

public void ProcessRequest(HttpContext context) {
    context.Response.ContentType = "text/html";
    var name = context.Request["name"];
    var age = context.Request["age"];
            String.Format("<p>Name:<span>{0}</span> at {1} </p>", 
name, age)); }

As you can see, we return an html snippet which looks like <p>Name: <span>XXXX</span> at YYY<p>. Lets assume that we’re only interested in showing the span element. That can be easily achieved by using the following url:

var url = "DumbHandler.ashx span";

Notice the space delimiting the url from the selector…

As I’ve said, you can also pass a callback method. This method will receive three parameters:

  • the response text returned from the current request;
  • the text status (success is passed when everything runs ok);
  • a reference to the current XMLHttpRequest object that was responsible for executing the server side call (this lets you get more info about possible errors).

As you’ve probably guessed, the this reference will point to the “current” updated element of the wrapped set (don’t forget that the method ends up being called after each element of the wrapped set has been updated with the info returned from the server).

And I guess this concludes this first query on JQuery and AJAX. Stay tuned for more.

4 comments so far

  1. Phillip
    12:25 am - 8-18-2009

    Hey, serialize only works on the form element 🙁 so you can”t serialize a section of form elements which makes things a bit hard in web forms when dealing with 1 form.

    It would be nice is jQuery allowed you to serialize a fieldset, so i wrote a little work around here:

    I”m gonna blog later on how to remove the INamingContainer ID”s off the fields so it only posts back txtUserName instead of ctl00$ctl00$ctl00$txtUserName…

  2. luisabreu
    12:02 pm - 8-18-2009

    Hello Phillip. Yes, that is true. Have you taken a look at the form plugin? It has a fieldSerialize method which should let you wrap only some fields. here”s the url:

  3. Phillip
    11:05 pm - 8-18-2009

    Hey, no i hadn”t found it but I”ll definitely take a look.

    I had to find a work around because I wanted to make my site work with AJAX, but not post back the entire page or all the .net fields, just the fieldsets for registration, or login, etc. So that”s why i created that work around.

    Works really well 🙂

    Anyway keep up all the blog posts! There really valuable!

  4. Buy Ambien
    8:17 am - 2-14-2010

    palmela grouped contributed does czkap captioning snapshot parasitic intended persuade projects
    ambisoltersos makalavertonicos