0

In my web application, on click on a specific button, AJAX call is triggered. On the server side, I want to execute a query to a DB.

Now, I am thinking about this, there are queries that are executing for some period, and maybe user isn't patient enough to wait for the results, and wants to stop the execution.

Is there a way to add one more button, that when clicked could stop previous AJAX call from executing and ALSO stop execution of a query? And is it a safe approach?

I am using angularjs, alongside with C# on server side.

2 Answers2

0

The best way to go about "cancelling" your request on the client side is by taking advantage of the $q service, creating a deferred and then attaching it to your request using the "timeout" property for the $http({}) function call.

function sendSomeRequestToServer() {
  var requestCanceler = $q.defer();

  var request = $http({
    method: "get",
    url: "/your/url",
    timeout: requestCanceler.promise
  });

  var promise = request.then(function(response) {
    return response.data;
  });

  promise._requestCanceler = requestCanceler;

  return promise;
}


function cancel(requestPromise) {
  if (promise && promise._requestCanceler && promise._requestCanceler.resolve) {  
    promise._requestCanceler.resolve();
  }
}

Most likely these functions would be wrapped in the same angular service. Credit to Ben Nadel and his blog for the tutorial and code.

Sean Larkin
  • 6,290
  • 1
  • 28
  • 43
0

related answers on your question

client side is streight forward

How to cancel/abort jQuery AJAX request?

but serverside is not as easy as client side, here related post to move forward

How do you cancel an AJAX long running MVC action client side (in javascript)?

Community
  • 1
  • 1
makison
  • 373
  • 2
  • 10