DEV Community

Cover image for How To Prevent Double Click in jQuery when Submitting Ajax
Code And Deploy
Code And Deploy

Posted on • Updated on

How To Prevent Double Click in jQuery when Submitting Ajax

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/jquery/how-to-prevent-double-click-in-jquery-when-submitting-ajax

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will show you how to prevent double click in jquery/javascript when submitting the button to ajax. This is important to implement because we don't know if your user doubled the click and it was submitted to your server. So here is the sample code below:

Basic Example

1. HTML Code

<button id="btnSubmit">Prevent Double Click</button>
Enter fullscreen mode Exit fullscreen mode

2. Javascript Code

$(document).ready(function() {

    $("#btnSubmit").on("click", function() {
        var $this = $(this);

        $this.attr('disabled', true);
    });

});
Enter fullscreen mode Exit fullscreen mode

As you can see above we have "$this.attr('disabled', true)". This function will help you to disabled the button when clicking but take not after we clicked the button will remain disabled. So next we will implement it using ajax and after the server responds to the client-side then we will remove the disabled attribute to the button.

Advance Example

1. HTML Code

<form action="save.php" id="form">
    <div class="form-group">
        <label for="email">Email</label>
        <input class="form-control" type="text" name="email">
    </div>
    <div class="form-group">
        <label for="first_name">First Name</label>
        <input class="form-control" type="text" name="first_name">
    </div>
    <div class="form-group">
        <label for="last_name">Last Name</label>
        <input class="form-control" type="text" name="last_name">
    </div>
    <div class="form-group">
        <label for="address">Address</label>
        <textarea class="form-control" type="text" name="address" rows="3"></textarea>
    </div>
    <button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

2. Javascript Code

$(document).ready(function() {

    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                //prevent double click and disable the button after click
                //also added content "Processing..." to the button
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                //remove the disabled button attribute
                $this.attr('disabled', false).html($caption);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

As you can see above code I added the disable function for the button "$this.attr('disabled', true).html("Processing...");" inside beforeSend() function on ajax. Then in the success() function on ajax a remove the disabled attribute/function so that the button will be clickable again after being submitted to the server.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/jquery/how-to-prevent-double-click-in-jquery-when-submitting-ajax if you want to download this code.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thank you for reading. Happy coding :)

Latest comments (1)

Collapse
 
rickydjr profile image
rickydjr • Edited

Hi, i'm looking to achieve what you described above.

I'm using the following code (not written by me as it's way beyond my understanding) to add records to a database but if the user double clicks the add record button the insert will add two or more rows.

My button:
Add Record

The code that does the insert:

    $(document).on('submit', '#saveStudent', function (e) {
        e.preventDefault();

        var formData = new FormData(this);
        formData.append("add_row", true);

        $.ajax({
            type: "POST",
            url: "code.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {

                var res = jQuery.parseJSON(response);
                if(res.status == 422) {
                    $('#errorMessage').removeClass('d-none');
                    $('#errorMessage').text(res.message);

                }else if(res.status == 200){

                    $('#errorMessage').addClass('d-none');
                    $('#AddModal').modal('hide');
                    $('#saveStudent')[0].reset();

                    alertify.set('notifier','position', 'top-right');
                    alertify.success(res.message);

                    $('#myTable').load(location.href + " #myTable");

                }else if(res.status == 500) {
                    alert(res.message);
                }
            }
        });

    });
Enter fullscreen mode Exit fullscreen mode

How could i stop this function being triggered twice like you've described in this post?

Many thanks for you help.