maxisme
maxisme

Reputation: 4255

Solution to accidental multiple enteries of form

I have the jquery/ajax:

$('form').bind('submit', function () {
     $.ajax({
         type: 'post',
         url: "Write-to.php",
         data: $("form").serialize(),
         success: function () {
             $.get("Data.php", function (data1) {
                 console.log(data1);
                 $(".data").html(data1);
                 scrolltobottom();
                 setFocusToTextBox();
                 $("#usermsg").val("");
             });
             $('.submited').show();
             $('.submited').html("S E N T");
             $("#usermsg").val("");

             setTimeout(function () {
                 $('.submited').fadeOut(1000);
             }, 2000);
         }
     });

     return false;
 });

But with this when I click enter I still have to wait for a bit before the $("#usermsg").val(""); which leads to accidental double enters because the user thinks they haven't sent the form when they actually have.

I have set up in the php, a function that does not allow any empty forms.

What can I do to prevent multiple entries?

Upvotes: 0

Views: 54

Answers (1)

Volkan Ulukut
Volkan Ulukut

Reputation: 4228

You can unbind the on submit after the form is submitted and bind another function with just return false; which prevents the form to be submitted again.

var submitting = 0;
$('form').bind('submit', function () {
     if(!submitting)
     {
         submitting = 1;
         $.ajax({
             type: 'post',
             url: "Write-to.php",
             data: $("form").serialize(),
             success: function () {
                submitting = 0;
                $.get("Data.php", function (data1) {
                     console.log(data1);
                     $(".data").html(data1);
                     scrolltobottom();
                     setFocusToTextBox();
                     $("#usermsg").val("");
                });
                $('.submited').show();
                $('.submited').html("S E N T");
                $("#usermsg").val("");

                setTimeout(function () {
                   $('.submited').fadeOut(1000);
                }, 2000);
            }
        });
     }
     return false;
 });

Upvotes: 1

Related Questions