Jacobian Jacobian - 5 months ago 14
Javascript Question

Prevent multiple form submits. Is there a simple solution

I do not know how to prevent multiple form submits in ajax. What I have seen on the Web by now are either non working solutions or real behemoths (tons of curvy code for such a microscopic task. what for?). What I have now is this code:

$('#btn').click(function(){
$('#form').submit(function(e){
var postData = $(this).serializeArray(),
formURL = $(this).attr('action');
$.ajax({
url:formURL,
type:'POST',
data:postData,
success:function(data, textStatus, jqXHR){

},
error:function(jqXHR, textStatus, errorThrown){

}
});
e.preventDefault();
});
});


I wish there was a one-stroke elegant solution, like some mysterious property or a function call.

Answer

What I usually do is disable submit on click to prevent more hits, and re-enable it when ajax is done:

$('#btn').click(function(){
  $(this).prop('disabled', true)  // disable submit to prevent multiple sends
  $('#form').submit(function(e){
    var postData = $(this).serializeArray(),
    formURL = $(this).attr('action');
    $.ajax({
        url:formURL,
        type:'POST',
        data:postData,
        success:function(data, textStatus, jqXHR){

        },
        error:function(jqXHR, textStatus, errorThrown){

        },
        always:function(){ // it its a success or a fail, we want to re-enable it
            $(this).prop('disabled', false) 
        }
    });
    e.preventDefault();
  });
});
Comments