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'] )
Put a redirector in the OK of the Insert... Then it goes back to the ADD page, or to which you direct.
– Sr. André Baill
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.
– Paulo Cavalcante