Ajax updating another request

Asked

Viewed 13 times

0

I have this ajax request that brings comments from a file (.php) TOGETHER WITH A FORM AT THE END to insert more comments:

//carregar comentarios 
  $(document).on('click','#carregar-comentario',function(){

    var id = $(this).attr("value");
    var retorno = $('#mostrar-comentario'+id+'');

      $.ajax({
          type: "GET",
              url: 'carregar-comentario.php',
               data: "id="+id,

        success: function(resposta) {
          retorno.fadeIn("fast").html(resposta);
              },
        beforeSend: function(){
          retorno.fadeIn("fast").html('<div>Corrigindo...</div>');
        },
        error: function(data) {
          retorno.fadeIn("fast").html('Erro ao corrigir!');
              }
          });

      return false;

  });

And the one who registers a new comment that came along with the comment list of the previous request.

//cadastrar comentario 
  $(document).on('click','#cadastrar-comentario',function(){

    var id = $('#id').attr("value");
    var id_usuario = $('#id_usuario').attr("value");
    var comentario = $('#comentario').val();
    var retorno = $('#mostrar-comentario-usuario'+id+'');

      $.ajax({
          type: "GET",
              url: 'cadastrar-comentario.php',
               data: "id="+id+"&id_usuario="+id_usuario+"&comentario="+comentario+"",

        success: function(resposta) {

          retorno.fadeIn("fast").html(resposta);


              },
        beforeSend: function(){
          retorno.fadeIn("fast").html('<div>Cadastrando...</div>');
        },
        error: function(data) {
          retorno.fadeIn("fast").html('Erro ao cadastrar!');
              }
          });

      return false;
  });

How do I make sure that when executing the second request (the registration), this new comment is displayed with the others automatically? Is there any way to take advantage of the first request by entering something in the Success of the second request? This would be the best way?

1 answer

0

There are several ways to do this; one of them is using .append()

This way the UI is processed all on the client without needing to data-driven , however, if the registration returns false, it is necessary to delete the element.

Example:

$( "#cadastrar" ).submit(function( event ) {
  event.preventDefault();
  valor = $('#item').val();
  $('#minhalista').append('<li>'+valor+'</li>');
  $('#item').val('');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="minhalista">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<form id="cadastrar">
  <input type="text" id="item" />
  <button>Cadastrar</button>
 </form>

I hope it helps

Browser other questions tagged

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