删除按钮上的表行单击使用Ajax

时间:2017-02-13 20:29:49

标签: javascript php html ajax sql-delete

我有一个包含4列的HTML表:SKU Group,Group_ID,Edit按钮和Delete按钮。我现在正在处理删除功能并且想要它,这样每当我按下删除按钮时,弹出一个确认框然后如果" OK"按下它,它将删除该行并发送删除查询,从数据库中删除它。

我知道我将使用Ajax和一个单独的PHP脚本来进行删除查询,但似乎无法弄明白。任何帮助表示赞赏!

删除按钮的HTML:

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

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:

<?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());
  }

?>

1 个答案:

答案 0 :(得分:1)

<强>的JavaScript

首先,我注意到你正在使用jQuery,为什么不尝试充分利用它呢?

首先为onclick按钮创建.delete事件处理程序。

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

您只想在用户确认已从数据库中成功删除 AND 后删除该行。

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
}

但是应该将data传递到$.post()以便我们知道要删除哪条记录?好吧,可能是我们要删除的记录的ID。

<强> HTML

由于您尚未发布大量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>

更改它,以便您可以轻松查找和访问组的ID,例如向您的单元格添加一个类。 (由于我们已经创建了onclick处理程序,因此您不再需要为onclick按钮使用.delete属性。)

<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(再次)

您可以通过遍历使用jQuery轻松找到关联的ID。现在把所有东西放在一起:

$('.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

人们使用预备语句的原因之一是防止攻击。你尝试使用它很好,但是你没有正确使用它(阅读周杰伦的评论)。 您希望将变量绑定到SQL中的参数。您可以通过在PDOStatement::execute()函数中传递变量数组来完成此操作。

删除记录时,通过使用PDOStatement::rowCount()检查受影响的记录数来检查记录是否有效。

我从来没有理由检查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
?>

当然,这还没有经过测试,因此可能存在很少的错误。如果您打开浏览器的控制台日志,则可以按照日志查看发生的情况。