Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
            console.error(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 jqXHR object has an abort method to cancel any ajax request. But in my ajaxRequest 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];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

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.

like image 403
WitVault Avatar asked Feb 06 '23 14:02

WitVault


1 Answers

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){
    this.ajaxRequest.abort()
  }
}

http://api.jquery.com/jquery.ajax/#jqXHR

like image 81
Blair Anderson Avatar answered Feb 09 '23 04:02

Blair Anderson