user10204501
user10204501

Reputation:

html form: prevent re-submitting while sending

I have this form:

<form action="" method="post" name="my_form">
    <input type="text" name="my_input">
</form>

You can write some text and the submit by pressing the enter key.

My problem: When you press the enter key multiple times, it'll also sent multiple times to my server.

There are solution like this:

onsubmit="my_button=true;return true;"

But these solutions require a submit button.

Is there a way to do this without adding a (hidden) submit button?

Upvotes: 0

Views: 206

Answers (4)

JamesBond
JamesBond

Reputation: 312

You could disable the button once it's set so the User cannot click it again

<form action="" method="post" name="my_form">
    <input type="text" name="my_input" <?php if(isset($_POST['my_input'])) { print 
    'disabled'; } ?>>
</form>

Upvotes: 0

some like this :

 <form onsubmit="send();" method="post" name="my_form">
    <input type="submit" name="my_input" id="sub">
 </form>

js code:

function send(){
    $("#sub").attr('disabled', 'disabled');
    $.ajax({
        // data
        success: function(data){
            $("#sub").attr('disabled', false);
        }
});
}

Upvotes: 1

Pieter De Clercq
Pieter De Clercq

Reputation: 1961

If you want to be absolutely sure, for example, submitting the form twice can cause severe damage/cause malicious things to happen, then you need to check this serverside. One rule of webdevelopment and general development is to never trust your end-user, and by simply blocking the form using JavaScript, you cannot be assured that a malicious user won't be sending the form twice by getting around the JavaScript.

What you can do is something like this:

Important: This is just a proof of concept example to explain the idea, this is not a 100% bulletproof solution.

Form

<?php
session_start();
$_SESSION['nonce'] = random_number();
?>
<html>
...
<form method="post" action="process.php">
<input type="hidden" name="nonce" value="<?php echo $_SESSION['nonce']; ?>" />
... other form elements ...
</form>
...

process.php

<?php
session_start();
$nonce = isset($_POST['nonce']) ? (int)$_POST['nonce'] : 0;
$session_nonce = $_SESSION['nonce'];

if ($_SESSION['nonce'] != $nonce) {
    die("Invalid nonce, double submission detected.");
}

$_SESSION['nonce'] += 1; // this will cause the previous check to fail on a second submission.

Upvotes: 2

Stefan Riedel
Stefan Riedel

Reputation: 21

Like this (untestet):

    var formSubmitted = false;
    document.getElementById('my-form').addEventListener('submit', function(){
    if(formSubmitted === false) {
        formSubmitted = true;
        return true;
    }
    return false;
});

Upvotes: 0

Related Questions