0

first of all, sorry for my bad english; secondly, iam really new with javascript, like know the concept but not have the full grip of the syntax; thirdly, the real problem is, i have idea to make a table that fetch data from database, and in the last column is an action button to show the detail of the row that been clicked, generating from database with ajax.

this my php code:

<?php $i=0; 
while($data=$query->fetch_assoc()){
    $i++;
    echo "<tr>";
    echo "<form action='' method='POST' id='show".$i."' role='form'>";
    echo "<td>"."<button type='submit' id='numb".$i."' value=".$data['num'].">";
    echo "detail</button></td>";
    echo "</form>";
    echo "</tr>";
}?> 

and this is my script:

<script> 
$(document).ready(function() {
  var len = $('[id^=show]').length;
  for (var i = 1; i <= len; i++) {
    var nn = "#numb" + i;
    $("#show" + i).submit(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "test.php",
        data: {
          numb: $(nn).val()
        },
        dataType: "html",
        success: function(response) {
          $("#container").html(response);
        }
      });
    });
  };
});
</script>

what iam trying is make multiple form with id like show, and count it in javascript, and then make function based on the how many id show in the table. but this code doesn't work, every detail button i click only return one data from the last parameter in the table. not data from the according row

Barmar
  • 741,623
  • 53
  • 500
  • 612
cadmad
  • 45
  • 1
  • 6
  • did you check the parameters of the ajax request? – K i Oct 11 '21 at 16:10
  • Why are you doing this with different IDs and loops? Use classes and DOM navigation methods. – Barmar Oct 11 '21 at 16:19
  • thanks for checking @ki, iam really new in javascript, like 2 days in mdn javascript, then have this idea and bugging me so i searched the script and modify it, and now after change the var with let, it work! – cadmad Oct 11 '21 at 17:02
  • thanks for the edited @Barmar would you mind give me example or link with using classes and DOM for this cases, please. im not so familiar with DOM so looping is the first thing come in my mind. – cadmad Oct 11 '21 at 17:04
  • 1
    `$(".show").submit(function() { var nn = $(this).find(".numb").val(); ...` – Barmar Oct 11 '21 at 17:06
  • 1
    Use `class="show"` for the form, and `class="numb"` for the button. – Barmar Oct 11 '21 at 17:07
  • wow, this journey is still sooooo long, thank you very much sir @Barmar , I hope you and your families are safe and healthy. – cadmad Oct 11 '21 at 17:13

0 Answers0