2

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

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Matt
  • 2,439
  • 7
  • 29
  • 42

5 Answers5

5

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.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
3

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;
            }
        });
epascarello
  • 204,599
  • 20
  • 195
  • 236
2
var $button = $(this);
$button.prop('disabled', true); // disable the button
$.ajax({
    url:"submit.php",
    type: 'POST',
    data: form,
    success: function (msg){                
        $(".ressult").html("Thank You!");
    },
    error: function (){
        $(".result").html("Error");
    },
    complete: function() {
        $button.prop('disabled', false); // enable it again
    }
});
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

Have you considered replacing your submit button with a loader image while the query executes, then re-adding it once the query is complete?

EDIT: Using the loader image is a sort of universal "I'm doing something" indicator, but disabling the button would work too!

Kirk H
  • 441
  • 2
  • 6
0

You could disable the submit button, before the ajax call is made. And then, if required, enable it on success.

eidsonator
  • 1,319
  • 2
  • 11
  • 25