Canceling a JavaScript / jQuery AJAX call

Technically, it’s not really canceled. I just wanted to say that straight away.

I had two drop down lists, the first with departments, and the second with supervisors in those departments. Choosing a value in the first DLL would populate the second DDL as well as loading a bunch of data to display on the page. The second DDL was populated quickly, but the rest of the data could take a while longer to display, and I wanted the users to be able to cancel the long-running request to see the supervisor-specific data.

One problem was that if I selected a supervisor while the department data was still loading, the supervisor-specific data would load, but when the call to the department-wide data finally finished, it would overwrite the supervisor data.

I was using the jQuery “$.ajax” method to call a Web API method. I had tried using the abort() method of the XMLHttpRequest object, the underlying object of the AJAX request, when the second DDL was changed. This didn’t work – the department data was still overwriting the supervisor data – so I had to get hacking.

Here is my solution. I created a variable called “processingRequest”. When the loadData function (which pulled the data from Web API) is started, the variable is set to “true”.  When the request completes, either successfully or it fails, the variable is set to false. Short-running requests will complete before any long-running requests, thus setting the “processingRequest” variable to false. When the long-running requests finished, it will see that the “processingRequest” variable isn’t true, and not perform the page update.

var processingRequest = false;
function loadData(supervisor, dept) {
    var theData = {
        'Supervisor': supervisor,
        'Dept': dept
    }
    processingRequest = true;
    var jqxhr = $.ajax({
        method: 'POST',
        contentType: 'application/json',
        url: uriToMyService,
        data: JSON.stringify(theData)
    })
      .done(function (d) {
          if (processingRequest) {
              populatePage(true);
              processingRequest = false;
          }
      })
      .fail(function (jqXHR, textStatus, errorThrown) {
          console.log('loadData error: ' + errorThrown);
          processingRequest = false;
      })
};

As I said in the beginning of the post, the request is not canceled, but the results of the request are never shown to the user.

Advertisements

,

  1. Leave a comment

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: