Get specific button with Jquery in repeat structure

0
while($reg = $stmt->fetch(PDO::FETCH_OBJ))
      {
         $id = $reg->id;

echo "<div class='altpost' id='$id'></div>";
        echo "<form id='$id' class='faltpost' method='post' action='altp.php'><input name='naltpost' type='number' value='$id' hidden/><button>editar</button></form>";
      }

jQuery(document).ready(function(){
        jQuery('.faltpost').submit( function(){
            var dados = jQuery(this).serialize();
            jQuery.ajax({
                url: "altp.php",
                type: "POST",
                data: dados,

                success: function(data)
                {
                    var id = $('.altpost').attr("id");
                    $(document.getElementById(id)).html(data);

                }

            });

            return false;
        });
    });

When I click on any button on any post it only activates the effect on the first post, the problem is that the buttons have the same name, so I'm looking for a way to specify each button. I tried jQuery ('. Faltpost'). Attr ("id"). Submit, but it did not work. the "$ id" is the number of the post, I'm taking a beating from JQUERY who help me and I'll give it a score.

    
asked by anonymous 28.07.2017 / 01:37

1 answer

1

What I would recommend doing is putting both% and% of the form within the same parent element. For example:

<div class="result">
    <div class='altpost'></div>
    <form class='faltpost' method='post' action='altp.php'>
        <input name='naltpost' type='number' value='$id' hidden />
        <button>editar</button>
    </form>
</div>

In this way, we can make the JavaScript code as follows:

// Tratamento do evento submit do formulário:
$(".faltpost").submit(function () {

    // Objeto do formulário que foi submetido:
    var form = $(this);

    // Recupera os dados a serem enviados:
    var dados = form.serialize();

    // Envia os dados através de AJAX:
    $.ajax({
        url: "alt.php",
        method: "post",
        data: dados,
        success: function (data) {

            // Objeto da div referente ao formulário:
            var div = form.parent(".result").children(".altpost");

            // Exibe o conteúdo na div:
            div.html(data);

        }
    }); 

});

The question is what to do:

var div = form.parent(".result").children(".altpost");

This will look for the parent element of the form that has the div class, then fetches this element a child element that has the .result class. This will then select the .altpost that is along with the form in div .

    
28.07.2017 / 02:34