Muiter
Muiter

Reputation: 1520

Prevent multiple form submit when using JS for submitting

I am using JS for submitting my forms. How can I prevent from user sending an form multiple times?

I have tried adding an onclick function to the button like:

<button type="button" class="btn btn-primary add_table_1" id="submit_add_table_1" onClick="this.disabled=true">Verstuur</button>

This does disable the button when clicking but the form is not submitted.

Any suggestions to prevent multiplessubmitting actions?

This is my JS code for submitting

$(document).ready(function () {
    $("#add_table_1").on("submit", function(e) {
        var postData = $(this).serializeArray();
        var formURL='processing/factuur_add.php';
        $.ajax({
            url: formURL,
            type: "POST",
            data: postData,
            success: function(data, textStatus, jqXHR) {
                $('#modal_add_table_1 .modal-body').html(data);
                $("#submit_add_table_1").remove();
            },
            error: function(jqXHR, status, error) {
                console.log(status + ": " + error);
            }
        });
        e.preventDefault();
    });

    $("#submit_add_table_1").on('click', function() {
        $("#add_table_1").submit();
    });
});

Upvotes: 0

Views: 61

Answers (1)

Shomz
Shomz

Reputation: 37701

You can disable the button just before firing your AJAX call and in case of an error, you can reenable it (just like you're already removing it upon success).

Something like this:

$("#add_table_1").on("submit", function(e) {
    $("#submit_add_table_1").prop('disabled', true);
    ...

Here's a simple example of simulating this with a 1-second response time:

$('#b').on('click', function(){
  $('#b').prop('disabled', true);
  $('#c').text(parseInt($('#c').text(), 10) + 1);
  setTimeout((()=>$('#b').prop('disabled', false)), 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="b">Submit</button>
<p>Click count: <span id="c">0</span><p>
<p>(try clicking the button multiple times)</p>

Upvotes: 1

Related Questions