How to abort pending jquery ajax request when user navigates to other page?
<p>I have defined a method to send jquery ajax request like this</p>

<pre><code>sendAjaxRequest(URL, data) {
    return $.ajax({
        type        : 'POST',
        url         : URL,
        crossDomain : true,
        data        : JSON.stringify(data),
        dataType    : 'json'
    }).fail((responseData) =&gt; {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
}
</code></pre>

<p>From the place of calling I keep the reference of ajax call </p>

<pre><code>this.ajaxRequest = sendAjaxRequest(Url, data);
</code></pre>

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

<p>From the docs I found that jquery <code>jqXHR</code> object has an <code>abort</code> method to cancel any ajax request. But in my <code>ajaxRequest</code> object I don't have any such method available. I am using <strong>jquery 2.2</strong>.</p>

<p>For clarification I also want to add that I am using <strong>react</strong>, and want to achieve this.</p>

<pre><code>  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();
  },
</code></pre>

<p>Taken from this <a href="https://facebook.github.io/react/tips/initial-ajax.html" rel="nofollow">link</a>.</p>

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

<p>I must be doing something wrong. Any help is appreciated.</p>