WitVault WitVault - 1 year ago 105
Ajax Question

How to abort pending jquery ajax request when user navigates to other page?

I have defined a method to send jquery ajax request like this

sendAjaxRequest(URL, data) {
return $.ajax({
type : 'POST',
url : URL,
crossDomain : true,
data : JSON.stringify(data),
dataType : 'json'
}).fail((responseData) => {
if (responseData.responseCode) {

From the place of calling I keep the reference of ajax call

this.ajaxRequest = sendAjaxRequest(Url, data);

and based on user navigation if user navigates away from page ( goes to another page on same website via router ) I want to cancel any pending ajax request.

From the docs I found that jquery
object has an
method to cancel any ajax request. But in my
object I don't have any such method available. I am using jquery 2.2.

For clarification I also want to add that I am using react, and want to achieve this.

componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url

componentWillUnmount: function() {

Taken from this link.

They basically say that When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

I must be doing something wrong. Any help is appreciated.

Answer Source

According to the ajax documentation, you're doing it properly. The $.ajax() function returns an object that has an abort function. You should check for existence of the function because it might not exist if the request has already finished.

componentWillUnmount: function(){
  if (this.ajaxRequest && this.ajaxRequest.abort){