Prevent double submission of forms in jQuery

后端 未结 22 1381
旧时难觅i
旧时难觅i 2020-11-22 08:10

I have a form that takes a little while for the server to process. I need to ensure that the user waits and does not attempt to resubmit the form by clicking the button agai

22条回答
  •  旧时难觅i
    2020-11-22 08:40

    If using AJAX to post a form, set async: false should prevent additional submits before the form clears:

    $("#form").submit(function(){
        var one = $("#one").val();
        var two = $("#two").val();
        $.ajax({
          type: "POST",
          async: false,  // <------ Will complete submit before allowing further action
          url: "process.php",
          data: "one="+one+"&two="+two+"&add=true",
          success: function(result){
            console.log(result);
            // do something with result
          },
          error: function(){alert('Error!')}
        });
        return false;
       }
    });
    

提交回复
热议问题