简体   繁体   English

使用Ajax单击按钮删除表行

[英]Delete Table Row on Button Click Using Ajax

I have an HTML table that has 4 columns: SKU Group, Group_ID, Edit button, and Delete button. 我有一个包含4列的HTML表:SKU组,Group_ID,“编辑”按钮和“删除”按钮。 I am working on the delete function now and want it so that whenever I press the delete button, a confirmation box pops up and then if "OK" is pressed, it deletes the row and sends a delete query which deletes it from the database. 我现在正在使用删除功能,因此希望每当我按下删除按钮时,都会弹出一个确认框,然后如果按下“确定”,它将删除该行并发送一个删除查询,该查询将从数据库中删除它。

I know I am to use Ajax and a separate PHP script for the delete query, but cannot seem to figure it out. 我知道我要对删除查询使用Ajax和单独的PHP脚本,但是似乎无法弄清楚。 Any help is appreciated! 任何帮助表示赞赏!

HTML for Delete Button: 删除按钮的HTML:

<td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td>

JavaScript...I know this needs some work but am posting it for the sake of my question: JavaScript ...我知道这需要做一些工作,但是出于我的问题而将其发布:

function deleteRow(r) {

if (confirm('Are you sure you want to delete this entry?')) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("skuTable").deleteRow(i);
  }



    request = $.ajax({
      type: "POST",
      url: "delete.php",
      data: i
    });


        request.done(function (response, textStatus, jqXHR){
          if(JSON.parse(response) == true){
            console.log("row deleted");
          } else {
            console.log("row failed to delete");
          }
        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {

        });


}

delete.php: delete.php:

<?php

  $SKU_Group = $_POST['SKU Group'];
  $Group_ID = $_POST['Group_ID'];

  $host="xxxxxx"; 
  $dbName="xxxxxx"; 
  $dbUser="xxxxxxxxxxxxxx"; 
  $dbPass="xxxxxxxxxxx";

  $pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

  $delete = "DELETE FROM SKU_Group_Dim WHERE Group_ID = '$Group_ID'";

  $stmt = $pdo->prepare($delete);
  $result = $stmt->execute();
  echo json_encode($result);
  if(!$result) {
      echo json_encode(sqlsrv_errors());
  }

?>

JavaScript JavaScript的

First, I noticed you are using jQuery so why not try utilizing it to its full potential? 首先,我注意到您正在使用jQuery,那么为什么不尝试充分利用它呢?

Start by creating an onclick event handler for your .delete buttons. 首先为.delete按钮创建一个onclick事件处理程序。

$('.delete').click(function () {
    // do something when delete button is clicked
});

You only want to delete the row after the user has confirmed AND it has been successfully deleted from the database. 你只想要删除行的用户已经确认它已经从数据库中删除成功后。

if (confirm('Are you sure you want to delete this entry?')) {
    // shorter call for doing simple POST request
    $.post('delete.php', data, function (response) {
        // do something with response
    }, 'json');
    // ^ to indicate that the response will be of JSON format
}

But what data should be passed into the $.post() so that we know which record to delete? 但是应该将哪些data传递到$.post()以便我们知道要删除的记录? Well, probably the ID of the record that we want to delete. 好吧,可能是我们要删除的记录的ID。

HTML HTML

As you have not posted much of the HTML, let's assume you built your table as below: 由于您没有发布太多的HTML,因此假设您按以下方式构建了表格:

<table class="skuTable">
    <tr>
        <td>123</td><!-- sku group -->
        <td>456</td><!-- group id -->
        <td><input type="button" class="edit" name="edit" value="Edit" ... ></td>
        <td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td>
    </tr>
    <!-- more similar records -->
</table>

Change it so that you can easily find and access the ID of the group such as by adding a class to your cells. 对其进行更改,以便您可以轻松地找到和访问该组的ID,例如通过向您的单元格中添加一个类。 (Since we have already created an onclick handler, you no longer need to use onclick attribute for your .delete buttons.) (由于我们已经创建了onclick处理程序,因此您不再需要为.delete按钮使用onclick属性。)

<table class="skuTable">
    <tr>
        <td class="skuGroup">123</td>
        <td class="groupId">456</td>
        <td><input type="button" class="edit" name="edit" value="Edit" ... ></td>
        <td><input type="button" class="delete" value="Delete"></td>
    </tr>
    <!-- more similar records -->
</table>

JavaScript (again) JavaScript(再次)

You can easily find the associated ID by traversing using jQuery. 您可以通过使用jQuery遍历轻松地找到关联的ID。 To put everything together now: 现在将所有内容放在一起:

$('.delete').click(function () {
    var button = $(this), 
        tr = button.closest('tr');
    // find the ID stored in the .groupId cell
    var id = tr.find('td.groupId').text();
    console.log('clicked button with id', id);

    // your PHP script expects GROUP_ID so we need to pass it one
    var data = { GROUP_ID: id };

    // ask confirmation
    if (confirm('Are you sure you want to delete this entry?')) {
        console.log('sending request');
        // delete record only once user has confirmed
        $.post('delete.php', data, function (res) {
            console.log('received response', res);
            // we want to delete the table row only we received a response back saying that it worked
            if (res.status) {
                console.log('deleting TR');
                tr.remove();
            }
        }, 'json');
    }
});

PHP PHP

One of the reasons people use prepared statements is to prevent attacks. 人们使用准备好的语句的原因之一是防止攻击。 It's good that you tried to use it, but you are not using it right (read Jay's comment). 您尝试使用它很好,但是您没有正确使用它(请阅读Jay的评论)。 You want to bind the variable to a parameter in your SQL. 您想将变量绑定到SQL中的参数。 You can do this by passing an array of the variables in the PDOStatement::execute() function. 您可以通过在PDOStatement :: execute()函数中传递变量数组来实现。

When you delete a record, you check whether it worked by checking the number of records affected using PDOStatement::rowCount() . 删除记录时,可以通过使用PDOStatement :: rowCount()检查受影响的记录数来检查它是否有效。

I've never had any reason to check whether execute() worked or not. 我从来没有任何理由来检查execute()是否有效。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

//$SKU_Group = $_POST['SKU Group'];

$Group_ID = $_POST['Group_ID'];

$host="xxxxxx"; 
$dbName="xxxxxx"; 
$dbUser="xxxxxxxxxxxxxx"; 
$dbPass="xxxxxxxxxxx";

$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

$stmt = $pdo->prepare("DELETE FROM SKU_Group_Dim WHERE Group_ID = ?");
$stmt->execute(array($Group_ID));

// send back the number of records it affected
$status = $stmt->rowCount() > 0;

// send back a JSON 
echo json_encode(array('status' => $status));

// nothing else can be outputted after this
?>

Of course, this has not been tested so there may be few bugs. 当然,这尚未经过测试,因此可能存在一些错误。 If you open up your browser's console log, you can follow the logs to see what is happening. 如果打开浏览器的控制台日志,则可以按照日志查看发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM