How to send record only once in INSERT

Asked

Viewed 485 times

2

Hello, I have an INSERT, sends, all great, but when it clicks several times on the Ubmit button, sends several, records, how can I avoid this?

Code:

<?php
    $id_noticia  = $edit["id"];
$autor = $_SESSION["username"];
$texto = $_POST["texto"];
$coment = "INSERT INTO `10cms_noticias_resp` ( `id_noticia` , `autor` , `texto`, `data` , `id`, `num` ) VALUES ('$id_noticia', '$autor', '$texto', now(), '', '')";

mysql_query($coment);
?>

Knob:

 <button type="submit" id="comentar" onclick="this.disabled = true;" style="width: 76px;height: 30px;color: white;font-size: 15px;line-height: 20px;border-radius: 50px;border: none;position: absolute;right: 0;background-image: linear-gradient(0deg, #FFA141, #FFB366 100%);margin-right: 10px;">enviar</button>
  • Put a redirector in the OK of the Insert... Then it goes back to the ADD page, or to which you direct.

  • Hello, you already have redirect, the problem is that it takes a while to load and send the records. So if the person clicks several times on the Submit button will send several records.

2 answers

1

In order to avoid multiple submissions of the same form, basic recommendations follow below:

1. Disable form submission

Once done the action of "Submit", disable it. Example of technique using Javascript:

<script type="text/javascript">
/**
Variável global "form_submited".
*/
window.form_submited = null;

/**
Função que verifica se a variável global possui o id do formulário que está sendo enviado.
*/
function AvoidMultiSubmit(frm)
{

    /**
    Instancia um objeto que receberá mensagens (erro, aviso, etc).
    */
    frm_message = document.getElementById("form_sent_message");

    /**
    Compara o id do formulário atual com a variável global. Se for diferente, proseggue com o envio.
    */
    if( form_submited != frm.id )
    {

        /**
        Atribui o id do form atual a variável global.
        */
        form_submited = form.id;

        /**
        Escreve mensagem de "loading".
        */
        frm_message.innerHTML = "Os dados estão sendo processados, por favor, aguarde.";

        /**
        Permite o envio.
        */
        return true;

    }else{

        /**
        Escreve mensagem de "waiting".
        */
        frm_message.innerHTML ="Por favor, aguarde o processamento dos dados.";

        /**
        Impede o envio.
        */
        return false;

    }
}
</script>

<div id="form_sent_message"></div>
<form id="frm1" onsubmit="return AvoidMultiSubmit(this);">
...
<form>

Why couldn’t you just turn off the button in the click action (onclick) ?

The reason is that a form can be submitted by means other than the click action. Therefore, the safest is to check in the event "Onsubmit".

2. Enhancing security with cookie

Preventing the multiple sending of a form is not enough because, in a simple "refresh", the user will still have the form "clean" to send again. In order to enhance security, we need to implement a cookie verification. The example below should be embedded within the "Avoidmultisubmit" function, in the conditional that sends the form:

    var name = "cookie_frm1"; // nome do cookie
    var value = "submited"; // um valor qualquer
    var days = 1; // quantidade de dias de expiração

    /**
    Formata os parâmetros
    */
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires=""+date.toGMTString();

    /**
    Cria o cookie
    */
    document.cookie = name+"="+value+expires+"; path=/";

In the PHP script that receives the data, check if the cookie exists:

if( isset( $_COOKIE['cookie_frm1'] ) )
{
    echo 'Ação negada';
    exit;
}

Note: Blocking in PHP can be a redirect or contain another type of user-friendly message. The above example is purely didactic.

When completing executions in PHP, if you don’t need to return to the form, remove the cookie:

unset( $_COOKIE['cookie_frm1'] )
  • Your code bugged my head. I put it straight, but it keeps sending alone when it enters the page.

  • if you just copied and pasted the code above thinking it would work like magic, then yes, you have problem, which is in your head.

0

Add a Javascript header to the button so that once it is clicked, it is disabled - no more clicks:

Via script (recommended):

document.getElementById('idDoBotao').addEventListener('click', function(event) {
    // event.target = quem acionou o evento
    event.target.disabled = true;
});

jQuery

var btn = $('#idDoBotao');
btn.on('click', function(event) {
    btn.disable(true);
});

Right on the button:

<input type="submit" onclick="this.disabled = true;">
  • Everything worked fine, but the problem is that when I open the page is as if he has already pressed Submit alone.

  • Is it already disabled the first time you load the page? Or after you have clicked once? Which of the options you used?

  • What you gave me was after clicking. Only when I load the page, it automatically gives Submit.

  • Weird. Is there any way you can put your button’s HTML code in the question? Are you using jQuery?

  • No, I’m not using jquery.

  • I tested it here and it runs normal: http://jsfiddle.net/nqoddff3/. Try clicking on the browser’s address bar and enter instead of giving F5, as the browser may be resending the form. Anyway, I think @Danielomine’s response is better, because as he said, a form can be submitted in several different ways, so listen to the event of click is not the best solution.

  • When I enter the page Submit sends the data alone, I wanted to send it only when I click the button.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.