Message appear automatically after sending

Asked

Viewed 237 times

1

I’m creating a mural, but I’d like to know how to do it so that when I click on the Publish button, the user’s message automatically appears in the div below the form, without the need for page refresh. Kind of like the Facebook posts. The database registration I know how to do, but jquery is not my strong suit.

<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>
  • What to do Ajax. The form is submitted to the same form page?

  • Hello dvd. This will be for the same page.

  • There’s no way you can create a . php file just to handle this?

1 answer

1


Add the jQuery code below that will capture the submit form and send to URL pagina.php (page to which the form will be sent. The name of the page you choose the one you want).

The return of Ajax 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'];.

The ideal is that you have a PHP file exclusively to receive requests from Ajax, which will return the HTML that will be inserted in div.

For example:

php page.

<?php

$msg = $_GET['mensagem'];

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

// retorno o HTML
?>
<strong><?=$msg?></strong>
  • Hello dvd. I have yes. Thanks again.

  • 1

    @Fox.11 Arrange. QQ thing we’re there :)

Browser other questions tagged

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