Francy
Francy

Reputation: 15

Pass the dynamic variable when button is pressed

I have create this example code:

    // Create connection
    $conn = Connection();

    $result = $conn->query("SELECT * FROM `users` WHERE 1");

  if ($result->num_rows > 0)
  {
    while($row = $result->fetch_assoc())
    {
      $name=  $row["name"] ;
      $id=  $row["id"] ;
      echo "<div class='media text-muted pt-3'>";

      echo "<button class='mr-2 rounded btn-primary icon32 select_c'></button>";

      echo "<p class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'>";
      echo "<strong class='d-block text-gray-dark'>". $name ."</strong>";
      echo  $id;
      echo "</p>";
      echo "</div>";
    }

I want to pass the id variable when the reference button is pressed using the post method. How can I do?

Upvotes: 0

Views: 46

Answers (1)

Simone Rossaini
Simone Rossaini

Reputation: 8162

You can use value on the button then use ajax:

echo "<button class='mr-2 rounded btn-primary icon32 select_c' value='".$row["id"]."' onClick='ajaxpost(this)'></button>";

Now use Ajax:

js:

function ajaxpost(elem) {
  var id = elem.value;

  $.ajax({
    url: "page.php",
    type: "POST",
    data: {
      id: id
    },
    success: function(data) {

      //what you want

    }
  });
}


            

Upvotes: 2

Related Questions