Graham Graham - 5 months ago 11
jQuery Question

Bypass AJAX request, but keep script going inside success statement

Is there a way to bypass an AJAX request from running, but still keep the script going inside the success statement? I have a condition that is either true or false. If it's false, the AJAX request should be bypassed. But I still want the script to continue within the nested success function. For this reason, I'm unable to use this code...

beforeSend : function(xhr, opts){
if(bypass_ajax == 1) {
xhr.abort();
}
},


Here's the code I'm trying to run...



var bypass_ajax = true;

$.ajax( {

url: destination_url,
data: { a:a, b:b },
type: 'POST',
success: function ( e ) {

if( bypass_ajax == true ) {

alert( 'Ajax request was manually bypassed, yet you can still read me...' );

}

}

});

Answer

No. If you abort the request then it isn't going to be successful.

Refactor your code so you have a reusable function instead.

function success() {
    // success function
}

if (bypass_ajax) {
    success();
} else {
    $.ajax(...).done(success);
}
Comments