OBAID OBAID - 2 months ago 7
jQuery Question

ajax abort is not working

I want to abort previous ajax request while starting new one i am using this code but its not working

<?php $urlToFetchPrice = 'getShippingAmount.php'; ?>
var $wk_jq = jQuery.noConflict();
$wk_jq('#weight').on('input', function() {
var $this = $wk_jq(this);
var $element = $wk_jq(this.element);
var previous_request;
if (previous_request) {
previous_request.abort();
}
previous_request = $wk_jq.ajax({
url: "<?=$urlToFetchPrice?>",
data: {
weight: $this.val(),
country: 'BH'
},
type: "POST",
dataType: "json",
format
success: function(data) {
console.log(data);
},
});
});


It's not showing any error in console but not aborting previous request. I have also tried this:

beforeSend: function() {
if (previous_request != null) {
previous_request.abort();
}


This also not working.

Answer

Move the var previous_request; to outside of your .on function. You defined it wrong place, so it will be empty always.

You can console.log / debug that too, to check does it has value.

var previous_request;
$wk_jq('#weight').on('input', function() {
   //.....
});
Comments