Dynamic forms on the same page in Jquery and PHP

Question:

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

I did this function using Jquery, but it doesn't work, when sending it just starts the page again. Does someone give 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>

Answer:

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 the 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>
Scroll to Top