Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make sure ajax request doesn't get fired multiple time

I was working on a simple form page and I was wondering what happens if someone clicks the submit button many many times (incase my shared hosting somehow seems to be slow at that time).

Also, incase anyone wants to look at my code

$.ajax({
    url: "submit.php",
    type: 'POST',
    data: form,
    success: function (msg) {
        $(".ressult").html("Thank You!");
    },
    error: function () {
        $(".result").html("Error");
    }
});

Is there a way to make it so after the user clicks it once, it won't run it again until the first click is done?

Thank you

like image 773
Matt Avatar asked Jul 30 '26 23:07

Matt


2 Answers

You can use jQuery's .one() function:

(function handleSubmit() {
    $('#submitBtn').one('click', function() {
        var $result = $('.result');
        $.ajax({
            url: 'submit.php',
            type: 'POST',
            data: form,
            success: function (msg) {
                $result.html('Thank You!');
                handleSubmit(); // re-bind once.
            },
            error: function () {
                $result.html('Error');
            }
        }); // End ajax()
    }); // End one(click)
}()); // End self-invoked handleSubmit()

*Edit: * Added recursion for multiple submissions.

like image 129
AlienWebguy Avatar answered Aug 01 '26 12:08

AlienWebguy


Use a boolean flag

 if (window.isRunning) return;
 window.isRunning = true;
 $.ajax({
            url:"submit.php",
            type: 'POST',
            data: form,
            success: function (msg){                
                $(".ressult").html("Thank You!");
            },
            error: function (){
                $(".result").html("Error");
            },
            complete : function () {
                window.isRunning = false;
            }
        });
like image 35
epascarello Avatar answered Aug 01 '26 13:08

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!