Im trying to resend ajax every 5 second if something went wrong but for some reason when i simulate offline connection with Chrom ajax request is called nonstop wtihout waiting 5 seconds after each request.
What im doing wrong ? btw im not getting any of thoes console.logs in my browser console
$('#filters-ajax').one('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
$.ajax({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
data: '&product_id=' product_id,
dataType: 'JSON',
timeout: 5000,
beforeSend: function(){
$('#btn-product-filter-groups').attr('disabled', true);
},
success: function(data){
$('#btn-product-filter-groups').attr('disabled', false);
},
error: function(xmlhttprequest, textstatus, message) {
console.log(xmlhttprequest);
console.log(textstatus);
console.log(message);
$.ajax(this);
}
});
})
CodePudding user response:
The timeout
property of the $.ajax()
options object does not define a delayed execution. Instead it is used to cancel a request if it has not been fulfilled within the specified time.
If you want repeated AJAX calls with a defined time between them to happen you will have to set it up with setTimeout()
or setInterval()
.
Here is a snippet with setInterval()
:
const url="https://jsonplaceholder.typicode.com/posts/";
const iv=setInterval(()=>
$.ajax({
url: url Math.ceil(Math.random()*50),
/* type: "POST",
data: '&product_id=' product_id, */
dataType: 'JSON',
/* beforeSend: function(){
$('#btn-product-filter-groups').attr('disabled', true);
}, */
success: function(data){
console.log(data.title)
},
error: function(xmlhttprequest, textstatus, message) {
console.log(xmlhttprequest);
console.log(textstatus);
console.log(message);
// $.ajax(this);
}
}), 1000);
document.querySelector("button").onclick=()=>clearInterval(iv)
<script src="https://code.jquery.com/jquery-3.6.2.min.js"></script>
<button>stop AJAX</button>