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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With