AJAX request with form is updating the page

Asked

Viewed 643 times

3

I am making a simple form to be sent with jQuery Ajax. Data is being sent, but is updating the normal page.

I would like to know what I am doing wrong, because when sending the form the page is being updated, but I wish that did not occur.

Follows 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>
  • Alter your .submit(function(){... for .submit(function(e){... and add right at the beginning of Function e.preventDefault(); before $(".listamensagem")..., I think it solves

2 answers

3


Clicking the Submit button is an event of the browser itself, it must be undone 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 in the correct way in jQuery, because it stops all jQuery handlers related to the button.

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

    e.stopPropagation();

    /* qualquer código */
}); 

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

Remembering that it is important to put the name of the event variable as function parameter, as the example: Function(and), otherwise it won’t work.

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

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

    return false;
});

2

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

Behold:

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

Or:

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

    return false;
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.