Cancel the submission of the jQuery form

2

Good afternoon, I have a form and I want it when the submit button is clicked it does not reload the page for sending the post I placed return false; in function submit of jQuery but did not roll .. .

$("#form-anuncio-edita-texto").submit(function () {
        if ($("#edita-anuncio-texto").val() !== "") {

            var formData = new FormData(this);

            $("#page-load").toggleClass('sk-loading');
            $("#anuncio-edita-text-alert").hide();
            $('#modal-anuncios-3').modal('toggle');

            var request = $.ajax({
                url: "modulos/paginas/" + identificador + "/process/updateMedia.php",
                method: "POST",
                data: formData
            });

            request.done(function (data) {
                $("#page-load").toggleClass('sk-loading');
                alert(data);
            });

            request.fail(function () {
                $("#page-load").toggleClass('sk-loading');
                toastNotification("<a href='index.php'>A página não pode ser carregada, se este erro persistir sujerimos que atualize a página ou clique <strong>AQUI</strong> e tente novamente.</a>", "Erro no Carregamento...", 15000, "error");
            });
        } else {
            $("#anuncio-edita-text-alert").show();
        }
        return false;
    });

When the field is empty it enters else and the page does not reload, but when I enter any value it reloads.

WARNING: This example is with a text field that would be easily resolved using the click function of jQuery storing content in var and putting it in data: {texto: vartexto} , but I can not use it because in that form has a FILE field where I will send a file via AJAX.

    
asked by anonymous 16.11.2017 / 17:14

2 answers

4

Use event.preventDefault () to prevent submit is executed, call the function by passing the event as a parameter.

Example:

$("#form-anuncio-edita-texto").submit(function(event){
   event.preventDefault();
});
  

event.preventDefault ()

     

Cancel the event if it is cancelable, without stopping the propagation of the event.

$("#form-anuncio-edita-texto").submit(function(event){
  event.preventDefault();
  console.log("Entrei mas não enviei");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formmethod="post" action="pagina2.asp" id="form-anuncio-edita-texto">
  <button type="submit" id="btn">
    Enviar
  </button>
</form>
    
16.11.2017 / 17:29
0

I think you have to do something like this:

<form id="form">
 <input type="text" name="name" id="name">
 <button type="button" id="submit">teste</button>
</form>

<script>
 $('#submit').click(function () {
   $('#form').submit();
 });
 $('#form').submit(function (e) {
   e.preventDefault();
   if //logica
 });
</script>
    
16.11.2017 / 17:44