douqingji3026 2014-07-03 13:20
浏览 80

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.

  • 写回答

3条回答 默认 最新

  • dousi1970 2014-07-03 13:28
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word