Message appears automatically after sending

1

I'm creating a mural, but I'd like to know how I can do that by clicking the Publish button, the user's message will appear automatically in the div below the form, without the need to refresh the page. Kind of like in Facebook posts. The registration to the database I know how to do, but jquery is not my strong.

<form method="post" class="form-control">  
  <div class="form-group">
    <label for="mensagem">Qual sua ideia?</label>
    <textarea name="Mensagem" class="form-control"></textarea>
  </div>
 <button type="submit" class="btn btn-primary">Publicar</button>
</form>

<div id="mostrarMensagens"></div>
    
asked by anonymous 04.01.2018 / 17:06

1 answer

1

Add the jQuery code below that will capture the submit of the form and send it to the URL pagina.php (page where the form will be sent.

The Ajax return will be dynamically inserted into div #mostrarMensagens :

$("form").on("submit", function(){
   var textarea = $("form textarea");
   var msg = textarea.val();
   $.ajax({
      url: 'pagina.php',
      data: { mensagem: msg },
      dataType: 'html',
      success: function(response) {
         $("#mostrarMensagens").append(response);
         textarea.val(''); // limpo o textarea
      }
   });
   return false;
});

In PHP, capture the form with $_GET['mensagem']; .

  

Ideally, you have a PHP file exclusively for receiving Ajax requests, which   will return the HTML that will be inserted into div .

For example:

page.php

<?php

$msg = $_GET['mensagem'];

// faço o que tem que fazer (inserir no banco etc)

// retorno o HTML
?>
<strong><?=$msg?></strong>
    
04.01.2018 / 17:38