even using preventDefault(); and Return false; Submit is running twice.
Note the comments:
$("#frmTeste").on('submit', function (e) { // AO SUBMIT
e.preventDefault(); // NÃO EXECUTAR O PADRÃO (SUBMIT) ????
alert('teste');
return false;
});
$("#btnTeste").on('click', function () { // AO CLICAR EM #btnTeste
$("#frmTeste").submit(); // SUBMIT NO FORMULÁRIO
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="frmTeste">
<input type="text" name="teste">
<button id="btnTeste">
Cadastrar
</button>
</form>
For this to work, you should put the preventDefault()
on the block that captures click the button, and not on the block that submits the form:
$("#btnTeste").on('click', function (e) {
e.preventDefault();
$("#frmTeste").submit();
});
But still, this is wrong! You can just put one button
with type="submit"
that would equal!
Solved the error in the code, let’s go to a solution:
intercept the event Ubmit, cancel it and via Ajax, perform the request
This, perhaps, is a solution to your question:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="frmTeste" action="" method="post">
<input type="text" name="teste">
<button id="btnTeste">
Cadastrar
</button>
</form>
<script type="text/javascript">
$('#btnTeste').on('click', function(e){
e.preventDefault(); // NÃO EXECUTA O SUBMIT, COMO ACONTECE NORMALMENTE
e.stopPropagation(); // IMPEDE QUE SEJAM EXECUTADOS OUTROS HANDLERS
$.ajax({
url: $('#frmTeste').attr('action'),
method: $('#frmTeste').attr('method'),
data: $('#frmTeste').serialize(),
beforeSend: function(){
// TUDO QUE ACONTECE ANTES DE EXECUTAR A REQUISIÇÃO AJAX
},
success: function(){
// TUDO QUE ACONTECE APÓS A REQUISIÇÃO (RESPOSTA DA REQUISIÇÃO)
// SE FOR EXIBIR ALGO REFERENTE A RESPOSTA, DEVE ADICIONAR O PARÂMETRO NA function(<parametro>){ //...
},
error: function(){
// TUDO QUE ACONTECE CASO OCORRA ALGUM ERRO NA REQUISIÇÃO
}
});
});
</script>
I haven’t tested the code, but I usually use the jQuery 1.2. I believe that in the version that you are using should reformulate the part of ajax with the .done
/ .error
...
I get it, my mistake was thinking that the
button
did not do thesubmit
by default!– Roberto de Campos