I have an ajax call
$('#button1').on('click', function(e){
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
enctype: 'multipart/form-data',
cache: false,
success: function(data){
},
error: function(){}
});
e.stopImmediatePropagation();
return false;
});
Now here the response is received after 10 minutes . So the ajax call is called multiple times. Why does this happen / how can we ensure that ajax call is called only once?
click(function(e) { e. preventDefault(); if ( $(this). data('requestRunning') ) { return; } $(this). data('requestRunning', true); $.
Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.
An alternative to disabling the button would be to use the .one() method and re-bind the event handler after callback:
var clickHandler = function(e){
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
enctype: 'multipart/form-data',
cache: false,
success: function(data){
$('#button1').one('click', clickHandler);
},
error: function(){}
});
e.stopImmediatePropagation();
return false;
}
$('#button1').one('click', clickHandler);
I was facing the same issue and it works when I set async: false
.
Sample code will be like this
$('#button1').on('click', function(e){
$.ajax({
url: url,
type: 'POST',
async: false,
dataType: 'json',
enctype: 'multipart/form-data',
cache: false,
success: function(data){
},
error: function(){}
});
});
Simply call .off()
right before you call .on()
.
This will remove all event handlers:
$(element).off().on('click', function() {
// function body
});
To only remove registered 'click' event handlers:
$(element).off('click').on('click', function() {
// function body
});
As per the answer by Brennan,
$('#button1').on('click', function(e){
$('#button1').attr('disabled', 'disabled');
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
enctype: 'multipart/form-data',
cache: false,
success: function(data){
$('#button1').removeAttr('disabled');
},
error: function(){}
});
e.stopImmediatePropagation();
return false;
});
Here the button will be disabled and will be enabled on success
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