Prevent ajax double call

I have 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 answer is received after 10 minutes. Thus, the ajax call is called multiple times. Why is this happening / how can we guarantee that the ajax call is called only once?

+7
source share
4 answers

An alternative to disabling the button is to use the .one () method and re-bind the event handler after the 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);
+26
source

I ran into the same problem and it works when I install async: false. An example code would be:

$('#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(){}
    });
});
+5
source

,

$('#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;
});

success

+4
source

Just call .off()right before the call .on().

This will remove all event handlers:

$(element).off().on('click', function() {
    // function body
});

To remove only registered click event handlers

$(element).off('click').on('click', function() {
    // function body
});
0
source

All Articles