Stop / Abort Ajax Request without startup error
I want to capture the whole ajax request on the page to stop / abort part of the request depending on some validation we are doing. Initially jqXHR.abort (); works, but the problem is that it fills the error event of the whole request that we aborted, which I don't want.
An example snippet of what I created as shown below.
var newajaxOptions;
$( ":button" ).on("click", function () {
var URL = "#";
$.ajax({
url: URL,
type: 'GET',
async: false,
success: function(){
alert("AJAX SUCCESS");
},
error: function(){
alert("AJAX ERROR");
}
});
});
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
alert("BLOCKED");
//set options to global variable so can re initiate ajax call later
newajaxOptions = ajaxOptions;
jqXHR.abort();
});
PS As a limitation, I am not allowed to make any changes to the ajax request, so I can only intercept the whole request validation on the details to stop the ones not allowed.
source to share
jqXHR can be really helpful
if(jqXHR.aborted)
return;
And Script:
var newajaxOptions;
$( ":button" ).on("click", function () {
var URL = "#";
$.ajax({
url: URL,
type: 'GET',
async: false,
success: function(){
alert("AJAX SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
if(jqXHR.aborted)
return;
alert("AJAX ERROR");
}
});
});
$( document ).ajaxSend(function(event, jqXHR, ajaxOptions) {
alert("BLOCKED");
//set options to global variable so can re initiate ajax call later
newajaxOptions = ajaxOptions;
jqXHR.abort();
});
Edit: Throw hack
var newajaxOptions;
$( ":button" ).on("click", function () {
var URL = "#";
$.ajax({
url: URL,
type: 'GET',
async: false,
success: function(){
alert("AJAX SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
//if(jqXHR.aborted)
// return;
alert("AJAX ERROR");
}
});
alert("After Button Click");
});
$( document ).ajaxSend(function(event, jqXHR, ajaxOptions) {
alert("BLOCKED");
throw "Your request is evil! Stop right now!";
});
In this case, this is something of a "hack". Throw
works in every browser and a side effect is interrupting the current stack. But be careful, alert("After Button Click");
it is also on the current stack and will never execute when you throw something.
More about:
source to share
you should be able to reset the error events in your ajaxSend
$( document ).ajaxSend(function(event, jqXHR, ajaxOptions) {
alert("BLOCKED");
//set options to global variable so can re initiate ajax call later
newajaxOptions = ajaxOptions;
ajaxOptions.error = null;
jqXHR.abort();
});
source to share