Dynamic forms on the same page in Jquery and PHP

Asked

Viewed 985 times

3

I’m trying to make a comment portal, and so will have a text input in each POST for people to comment, these POSTS will be on the same page (Facebook style), as well as inputs, which will have to be dynamic.

I did this function using Jquery, but it doesn’t work, when sending just start the page again. Someone gives me a light?

HTML:

    $(document).ready(function() {
    
        function enviarcomentario(id) {
    
            var iconCarregando = $('<img src="loading.gif" width="70" /> <span class="destaque">Carregando. Por favor aguarde...</span>');
            $('#formcomentario' + id).submit(function(e) {
    
                    if ($("#texto" + id).val() === '') {
    
                        $('#texto' + id).select();
                        return false;
                    } else {
    
                        e.preventDefault();
                        var serializeDados = $('#formcomentario' + id).serialize();
    
                        $.ajax({
                            url: 'acoes.php?enviarcomentario=1',
                            dataType: 'html',
                            type: 'POST',
                            data: serializeDados,
                            beforeSend: function() {
                                $('#statuscomentario' + id).html(iconCarregando);
                                $('#send' + id).attr('disabled', 'disabled'); //desabilito
                            },
    
                            complete: function() {
                                $(iconCarregando).remove();
                            },
    
                            success: function(data, textStatus) {
    
                                $('#send' + id).removeAttr('disabled'); //habilito
    
                                $('#texto' + id).val("");
    
                            },
                            error: function(xhr, er) {
                                $('#formcomentario' + id).html('<p class="destaque">Error ' + xhr.status + ' - ' + xhr.statusText + '<br />Tipo de erro: ' + er + '</p>');
                            }
    
                        });
    
                    }
                }
    
            );
        }
    });
<form action="" method="POST" id="formcomentario<?php echo $row['idd']; ?>">
        <img class="img-responsive img-circle img-sm" src="<?php if($user['imagem']) { ?>fotos/<?php echo $user['imagem']; } else { ?> estilos/img/sem-foto.png<?php } ?>" alt="Alt Text">
        <!-- .img-push is used to add margin to elements next to floating images -->
        <div class="img-push"><input type="hidden" name="idp" value="<?php echo $row['idd']; ?>">
            <input type="text" class="form-control input-sm" id="texto<?php echo $row['idd']; ?>" name="texto" placeholder="Escreva um comentário">
            <input type="submit" onclick="enviarcomentario(id)" style="display: none;"> 
    
            <div id="statuscomentario<?php echo $row['idd']; ?>"></div>
        </div>
    </form>

  • 1

    at what point you are executing the function: enviarcomentario(id)?

  • <input type="Submit" onclick="send comment(id)" style="display: None;"> I’ve tried that too and won’t

  • you need to add the eventlistner submit( before clicking and sending... remove it from that function and find another way to get the ID you need, such as a hidden field or date or action attribute of the form.

  • I don’t know how to do it, I’ve already searched the whole Google, and I don’t understand how

1 answer

2


When you need to work with multiple similar elements that use the same function, always prefer to use class instead of ID, in your case it would be something like this: (also analyze the modifications in html)

$(function() {

  $('.formcomentario').submit(function(e) {
    var form = $(this); // instancia exatamente o formulario a ser enviado na var form
    if ($("[name=texto]", form).val() === '') {

      $("[name=texto]", form).select();
      return false;
    } else {

      e.preventDefault();
      var serializeDados = form.serialize();
      var iconCarregando = $('<span class="destaque loading"><img src="loading.gif" width="70" />  Carregando. Por favor aguarde...</span>');

      $.ajax({
        url: form.attr("action"), // faça o form funcionar sem jquery e aqui use o mesmo action original
        dataType: 'html',
        type: 'POST',
        data: serializeDados,
        beforeSend: function() {
          $('.statuscomentario', form).html(iconCarregando);
          $('#send' + id).attr('disabled', 'disabled'); //desabilito // (não encontrei esse elemento)
        },

        complete: function() {
          $('.statuscomentario', form).html('');
        },

        success: function(data, textStatus) {

          $('#send' + id).removeAttr('disabled'); //habilito // (não encontrei esse elemento)

          $("[name=texto]", form);

        },
        error: function(xhr, er) {
          $(form).append('<p class="destaque">Error ' + xhr.status + ' - ' + xhr.statusText + '<br />Tipo de erro: ' + er + '</p>');
        }
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="acoes.php?enviarcomentario=1" method="POST" class="formcomentario">
  <img class="img-responsive img-circle img-sm" src="<?php if($user['imagem']) { ?>fotos/<?php echo $user['imagem']; } else { ?> estilos/img/sem-foto.png<?php } ?>" alt="Alt Text">
  <!-- .img-push is used to add margin to elements next to floating images -->
  <div class="img-push">
    <input type="hidden" name="idp" value="<?php echo $row['idd']; ?>">
    <input type="text" class="form-control input-sm" name="texto" placeholder="Escreva um comentário">
    <input type="submit" style="display: none;">

    <div class="statuscomentario"></div>
  </div>
</form>

  • Thank you very much, but it only stays on loading, as I do to recover the id of the post at the time I send?

  • I already understood how to recover the POST through the input that is Hidden, I just do not understand why it keeps loading and will not

  • Uncaught Referenceerror: id is not defined(...)

  • I already found the error, it was because I was doing the Ubmit business wrong, now just sending everything right, you are a genius, just need to find out why not erasing the input

  • can, val("") was missing; $("[name=text]", form)

Browser other questions tagged

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