skip to Main Content

I have a problem. I want to exchange certain data using PHP, MySQL and Ajax.

To do this I always have to pass the ID of a field to my backend, so I can continue working with this ID.

How do I pass the value from my button to my URL in Ajax?
What do I have to consider?
row[‘id’] is my variable (PHP)

HTML Code:

<a class='commentSikayet'>
  <button id='commentSikayet' name='commentSikayet' value='{$row['id']}'>
    Şikayet et
  </button>
</a>

Ajax:

$(document).ready(function () {
  $("#commentSikayet").click(function () {
    $.ajax({
      url: 'report_comment.php',
      type: 'POST',
      data: {bar: $("#bar").val()},
      success: function (result) {
        alert('Erfolgreich gemeldet.');
      }
    });
  });
});

2

Answers


  1. Since you’re listening for the click event on the button, you can access it via this in your handler function.

    Add the name / value pair to your AJAX data option

    $("#commentSikayet").on("click", function (e) {
      e.preventDefault();
      $.post("report_comment.php", {
        bar: $("#bar").val(),
        [ this.name ]: this.value // add name / value in here
      }).done(function (result) {
        alert('Erfolgreich gemeldet.');
      });
    });
    

    This will include commentSikayet=rowIdValue in the POST request body which you access on the PHP side via…

    $rowId = $_POST["commentSikayet"];
    
    Login or Signup to reply.
  2. Assuming there might be more than one data sets in your page I modified your example to the following snippet. Each buttons has a data-id attribute that identifies the current dataset (the id would be supplied through your PHP script as $row["id"]):

    $("body").on("click","button", function(ev){
      ev.preventDefault(); // prevent submitting a form ...
      let data={cmt_id: $(this).data("id"),
                value: $(this).prev().val()}
      $.post("https://jsonplaceholder.typicode.com/comments",data)
       .done(function (result) {
         console.log("Erfolgreich gemeldet:",result);
      });
    });
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <div><input type="text" value="some text">
    <button name="commentSikayet" data-id="123">Şikayet et</button></div>
    <div><input type="text" value="some other text">
    <button name="commentSikayet" data-id="124">Şikayet et</button></div>
    <div><input type="text" value="more text">
    <button name="commentSikayet" data-id="125">Şikayet et</button></div>

    In your backend PHP script (taking the place of the above typicode-URL) you can pick up the values from the $_POST superglobal as

    $_POST["cmt_id"]; // id value
    $_POST["value"];. // actual text content
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search