PHP - 使用按钮删除数据

I'm trying to create a HTML table that lists all the rows in a database table. Then, next to each row I want to have a button so the user can delete that entry. I have created the table but I can't get the buttons to work.

I have been searching around and I found this post How to Call a PHP Function on the Click of a Button but I can't get it to work. I've never used ajax before so I might not understand the code correctly.

Here is the code:

Go through all the data from the table and create a button for each entry

<?php
for ($x = 0; $x < sizeof($data); $x++) {
?>
     <input type="submit" class="tableButton" name="<?php echo $x ?>" value="<?php echo $x ?>">
<?php
}    
?>

When a tableButton is clicked, send its value to ajax.php

$('.tableButton').click(function () {
    var clickBtnValue = $(this).val();
    var ajaxurl = 'ajax.php',
    data = { 'action': clickBtnValue };
    $.post(ajaxurl, data, function (response) {
    });
});

ajax.php

Get the value of the button that was pressed and do something with it

<?php
if (isset($_POST['action'])) {
    $data = $_POST['action'];
    echo $data;
}
?>

Currently I just have it echo the value to test it but it's displaying nothing. What I would have it do is run this query:

 DELETE from myTable WHERE id = $data;

Or if someone knows a better way to do this please let me know.

Edit

After doing a lot more searching I found out why this wasn't working how I expected. As I suspected since I've never used AJAX before there was something I missed, I didn't know the echo wouldn't print directly to the screen. I just changed the echo to a delete query and tested that and it works... So the code is fine, but I think I should learn AJAX sometime. Thanks for all the responses.

I'm also aware of the sql injection that is possible here, this was just a quick mock-up, thanks.

It is hard to help you from this point of view we got.

You should do some debugging, like:

  1. Check if the associated ajax.php is called (by checking the console with "F12" for example)
  2. If yes, check the data being passed through your ajax POST
  3. If not, maybe the reference link is wrong

Let me hear what you got.

Ok. First of all you need to create the button with row id. You can do it using mySQL and PHP loops. Create it in this following format.

<input type="submit" name="test" data-id="23" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="24" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="25" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="26" value="Remove" class="delete_row" />  

Here replace the data-id in each button with the id of row you are looking to delete.( Replace 23,24 etc with database ids dynamically ).

Java script

$(document).ready(function(){

    $(".delete_row").click(function(e){

        e.preventDefault();
        var deleteId = $(this).attr("data-id");//unique id of the raw to be deleted

        var request = $.ajax({
        url: "ajax.php",
        type: "POST",
        data: { id : deleteId },
        dataType: "json"
        });
        request.done(function( msg ) {

           if( msg.status )
               alert("Deleted successfully!");
           else
               alert("Something gone wrong!!");
        });
        request.fail(function( jqXHR, textStatus ) {
           alert( "Request failed: " + textStatus );


        });

    });


});

ajax.php

<?php
   /* AJAX check  */
   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

       $delete_id = $_POST["id"];
       if( is_numeric( $delete_id ) ){

            /*DELETE QUERT WHERE id = $delete_id (Try to use mysqli or PDO ) */
            /* $affected_rows = effected_rows() */

            if( $affected > 0 ) 
            {
                echo json_encode( array("status" => true ) );die;
            }

        }
        echo json_encode( array("status" => false ) );die;
     }
     die("Get out of here!");
?>

I hope this will help you :)

You can try by this way. I think it will help you

Html File

<html>
<head>
<title>Test</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('.tableButton').live('click', function(){
    var id = $(this).val();
    $.ajax({
        url:'ajax.php'
        ,data:{id:id}
        ,type:'post'
        ,success:function(data){
            if(data == 'success'){
                $('#' + id).remove();
            }
        }
    });
});
</script>
<?php
  for ($x = 0; $x < 5; $x++) {
?>
<input type="submit" class="tableButton" id="<?=$x?>" name="<?php echo $x ?>"value="<?php echo $x ?>">
<?php
 }
 ?>
 </body>
 </html>

ajax.php

<?php
if(isset($_POST['id'])){
    $id = $_POST['id'];
    //delete operation here
    //if(deleted) echo 'success';
}
?>