0

trying to call php function on button click to delete row from db which i'm looping... need to pass button tag id attribute to the function. cant get it work

$('button').click(
    function(){
        var id = $(this).attr('id');
        $.ajax({
            url: "ins.php",
            type: "POST",
            data: id,
            success: function(data){
            }
        });
    });

// html button in table to delete a row
<td><button id='.$i.' name="delete"><img src="delete.png"></button></td>

// ins.php
if (isset($_POST['delete'])){
    DB_delete($conn, $_POST['delete']); 
}

// function that deletes the row
function DB_delete($conn,$id){

    $sql = "DELETE FROM person WHERE id = ?";

    $stmt=$conn->prepare($sql);
    $stmt->bind_param('i',$id);
    $stmt->execute();
    $stmt->close();
}

2 Answers 2

1

You're simply not passing the data correctly. Since you're looking for the $_POST['delete'], then you must submit it with that key/value.

$.ajax({
      url: "ins.php",
      type: "POST",
      data: {"delete": id},
      success: function(data){
      }
  });
Sign up to request clarification or add additional context in comments.

Comments

0

Your data parameter in ajax call is not right. Now it's just a plain number, but it should be an object in order to be treated as $_POST or $_GET (depending on the 'type' parameter) in your ins.php. So it should be like this:

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

1 Comment

What do you get, when you run var_dump($_POST['delete']) in your ins.php?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.