even using preventDefault (); and return false; submit is running twice.
Notice 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><formid="frmTeste">
<input type="text" name="teste">
<button id="btnTeste">
Cadastrar
</button>
</form>
For this to work, you should put preventDefault()
in the block that captures the click of the button, not the block that submits the form:
$("#btnTeste").on('click', function (e) {
e.preventDefault();
$("#frmTeste").submit();
});
But, still, this is wrong! You can simply put a button
with type="submit"
that would give it!
Uncovered the error in the code, let's get a solution:
intercept the submit event, 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><formid="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 have not tested the code, but I usually use jQuery 1.2 . I believe that in the version you are using you should reformulate the ajax part with .done
/ .error
...