Request Form AJAX is updating page

2

I'm making a simple form to be submitted with jQuery Ajax. Data is being sent, but you are updating the normal page.

I would like to know what I am doing wrong, because in submitting the form the page is being updated, but I would like this not to happen.

Follow the codes:

Ajax:

$(document).ready(function() {
$(".enviamensagem").submit(function (){     
    $(".listamensagem").html("<h4>Carregando Mensagens</h4>");      
    var formdata = $(".enviamensagem").serialize();
    $.ajax({
        type:"POST",
        url:"dados.php",
        data: formdata,
        beforeSend: function(){
        },
        success:function(data){           
          $("#areamsg").html(data);           
        }
    });
}); 

});

HTML:

<form method="post" class="enviamensagem">
    <fieldset>        
      <label >Escrever Mensagem: 
          <textarea name="mensagem" required></textarea></label>               
          <input type="submit" class="botao" id="btnenviamsg" value="Enviar" />           
     </fieldset>
</form>
    
asked by anonymous 13.12.2016 / 18:34

2 answers

3

Clicking the submit button is an event of the browser itself, it must be canceled to use an ajax. There are different ways to do this.

e.preventDefault () - works in most cases, but does not prevent the execution of other handlers that may be associated.

$(".enviamensagem").submit(function(e){ 
    /* qualquer código */

    e.preventDefault();

    /* qualquer código */
}); 

e.stopPropagation () or e.stopImmediatePropagation () - Stops the event correctly in jQuery, because it interrupts all jQuery handlers related to the button.

$(".enviamensagem").submit(function(e){ 
    /* qualquer código */

    e.stopPropagation();

    /* qualquer código */
}); 

The above jQuery methods can be used in any part of the function code, but it is recommended that you use it at the beginning of the function.

Remembering that it is important to put the event variable name as a function parameter, for example: function ( and ), otherwise it will not work.

return false - Stops the event in native javascript, which DOES NOT respect the specific jQuery handlers and in DOM2 does not work.

$(".enviamensagem").submit(function(){ 
    /* qualquer código */

    return false;
});
    
13.12.2016 / 21:50
2

You can use event.preventDefault() or else give return false in the submit function. This is to prevent page submission

See:

$(".enviamensagem").submit(function (e){     
   e.preventDefault();
   // resto do código
});

Or:

$(".enviamensagem").submit(function (e){     
    // resto do código

    return false;
});
    
14.12.2016 / 20:17