Coordinating AJAX Requests with jQuery

I was working on a requirement where I had to run the same AJAX post request multiple times, in this case to close out multiple trades in a system. I then had to route to another page if successful, or display an error message if an error occurred.

I started by looping through the AJAX calls using jQuery.each, but I quickly realized that this wasn’t going to work without using a global boolean within the .ajax success callback. I then found a Stack Overflow post that highlighted that jQuery.when can be used to group AJAX calls as “deferred objects,” allowing you to coordinate multiple calls and then run a function after they are all complete.

First I wrapped my jQuery.ajax call in a function.

function postClose(closeObj, reroute)
{
    return $.ajax({
        type: "POST",
        url: "/Trades/Close",
        data: closeObj,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function (data) {
            if (reroute) {
                window.location.href = "/Trades";
            }
        }
    });
}

Then I added the following code to a click handler for the “Close Selected” button on my page. This builds up the defers array with deferred objects, which are essentially calls to the postClose method, above. Then it uses .when to execute the AJAX calls. Once they are all complete, the function in .done executes the final AJAX call, which routes the user to another page upon success.

    
$('#multi-close-btn').click(function () {
    var trades = closeCombinedTrades.GetSelectedItems();
    var defers = [];
    var close;
    $.each(trades, function (i, val) {
        close = new Close(val.value, closeMethod.GetValue(), closeCloseDt.GetDate(), closeTradeStatus.GetValue());
        defers.push(postClose(close,false));
    });
    $.when.apply($, defers).done(function () {
        close = new Close($('#Trade_TradeId').val(), closeMethod.GetValue(), closeCloseDt.GetDate(), closeTradeStatus.GetValue());
        postClose(close, true);
    }).fail(function () {
        alert("An issue occurred while closing the trades. Please contact the administrator.");
    });
});
Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: