Using jQuery's Ajax Method

Dive into jQuery's 'big gun': the ajax method, useful for handling scenarios when using the more convenient load, get, or post methods is not an option

Don Kiely

August 10, 2011

6 Min Read
three office people staring at a piece of paper

Most of the Ajax features in jQuery, such as the very easy-to-use load, get, and post methods, are convenience methods that make using Ajax fairly easy for the most common scenarios. But when those convenience methods don't work for you, you can pull out the big Ajax gun in jQuery: the ajax method. This is the method that all the convenience methods ultimately use to make the actual call to the server. They do this by performing all the necessary setup and setting default values for various arguments that work for the particular Ajax task at hand.

You can use the ajax method directly to handle the scenarios not easily handled—or not handled at all—by the convenience methods. The ajax method has the deceptively simple syntaxes shown below, taking just one or two arguments, url and options. With the first syntax option, you can pass the URL for the target web service and optionally follow it with as many option settings as you need. Or you can just pass a value for the options argument, one of which could be the url. This method is the embodiment of the saying that the devil is in the details, and providing the right options for what you want to do is the details you need to wade through to make the method work for you.

jQuery.ajax( url, [ options ] )jQuery.ajax( options )

If you look at the documentation for the ajax method on the jquery.com website, you'll find that there are more than 30 option settings you can use. There are a handful of options you'll use all the time, and many more that handle various esoteric situations. There are options that let you define event functions, control the response data format, give you access to the underlying XHR object, define additional request headers, and many, many more.

As you explore the options, it becomes easy to appreciate all the work that the convenience methods do for you. On the other hand, it is nice to have the option to use the ajax method directly.

Using the Ajax Method

Let's look at a simple example of using the ajax method by writing a Hello World application. The page calls the HelloWorld web service method to return a string. One way to do this is to use the very simple load method within a page:

$(function () {    $('#buttonSays').click(function () {        $('div').load('AjaxServices.asmx/HelloWorld');    });});

But you can also use the ajax method directly to make the Ajax call to the server. The following code uses the type option to make a GET call and the url option to specify the location of the web service. Like the get and post methods, the ajax method is a utility function that doesn't directly update a matched set of elements, so the method call uses the success event option to define a function to update the div elements on the page with the response text. This anonymous function uses the text method of the response object to extract the text from the XML returned from the web service method and the html method to update the div elements.

$(function () {    $('#buttonSays').click(function () {        $.ajax({            type: 'GET',            url: 'AjaxServices.asmx/HelloWorld',            success: function (response) {                $('div').html($(response).text());            }        });    });});

The screenshot below shows the results of clicking the Get Info button on the page. The result is the same as the earlier sample using the load method, where the code updates the three div elements on the page. The web service increments the number with each call, so that you know how many times it has run.

As you can see, using the ajax method is more complex than using the load method, both because you have to provide appropriate option values and because the method doesn't directly update a matched set of elements. You have to write a function for the success event to update the page.

The next sample is a bit more complex and realistic. The Boroughs.html page, shown in the screenshot below, displays information about some of the boroughs in Alaska when the user clicks the Get Boroughs button. A real web page might let the user filter the data in some way, but this sample simply grabs the information from the server and updates the page.

The body section of the page, shown below, is quite simple, consisting of a header, button, and div to receive the data.

    Alaska Boroughs            Get Boroughs    

The page calls a GetAllBoroughs web service method, which uses a Borough class to hold the data about each borough and a generic List object to hold the collection, as shown in the following code.

public class Borough{    public string Name { get; set; }    public int Population { get; set; }    public short Created { get; set; }}List Boroughs = new List{    new Borough{Name = "Fairbanks North Star Borough",         Population = 82840, Created = 1964},    new Borough{Name = "Municipality of Anchorage",         Population = 260283, Created = 1975},    new Borough{Name = "Denali Borough", Population = 1893,         Created = 1990},    new Borough{Name = "City and Borough of Juneau",         Population = 30711, Created = 1970},    new Borough{Name = "North Slope Borough",         Population = 7385, Created = 1972}};

The GetAllBoroughs web method simply returns the List object with the collection of boroughs. The code doesn't need to specify the format of the data; that's a detail that jQuery and the web service will work out together.

[WebMethod]public List GetAllBoroughs(){    return Boroughs;}

The following code in the web page makes the Ajax call to this web method. The method will make a POST call to the specified URL, providing an empty object literal as the data for the call. The content it wants back is JSON, specified in both the contentType and dataType options. The success option defines an event function to update the page, adding a p element with a description, a ul element with id boroughList, and looping through each row of data to build an li element with the data. Notice that the append method in the loop appends each new li element to the ul element that was earlier added dynamically. You're not limited to appending elements to elements in the original page source.

$(function () {    $('#buttonGet').click(function () {        $.ajax({            type: "POST",            url: "AjaxServices.asmx/GetAllBoroughs",            data: "{}",            contentType: "application/json; charset=utf-8",            dataType: "json",            success: function (response) {                $('#divResult').html('')                    .append('Here are a few of Alaska                     boroughs:');                var boroughs = response.d;                for (var i = 0; i < boroughs.length; i++) {                    $('#boroughList').append(''                        + boroughs[i].Name + ': '                        + boroughs[i].Population +                             ' people, created in '                        + boroughs[i].Created                        + '');                }                $('#divResult').css('display', 'block');            }        });    });});

The number of options you set for the ajax method is highly dependent on what you need to accomplish with the method call. Recall that the web method didn't have anything that told it that the client would want JSON data. The ajax method requested the data in that format, and the web method delivered, as shown in Firebug in the screenshot below. Notice, too, that the action was a POST, as requested.

Most of the time, the load, get, and post Ajax methods in jQuery will do what you need. But when you need more control, check out the ajax method!

I adapted this material from a jQuery course I wrote for AppDev.

Don Kiely ([email protected]), MVP, MCSD, is a senior technology consultant, building custom applications and providing business and technology consulting services. His development work involves SQL Server, Visual Basic, C#, ASP.NET, and Microsoft Office.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like