0

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();
    });
});
2
  • "Any suggestions to prevent multiplessubmitting actions?" - You could remove the button. Like you already do ($("#submit_add_table_1").remove()) o.O Commented Nov 16, 2019 at 10:30
  • 1
    @Andreas That happens in the success callback, so technically you are able to click it multiple times before it gets removed, depending on the request speed. Commented Nov 16, 2019 at 10:32

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.