如何使用AJAX从MySQL数据库中删除HTML行和删除条目?

时间:2016-08-11 19:54:33

标签: php jquery html mysql ajax

我目前正在使用HTML,PHP,Javascript和AJAX的组合来创建HTML,从MySQL数据库中的表填充它,然后添加表的内部以便同时删除行,并从MySQL数据库中删除条目。这就是我目前所拥有的:

<?php

echo '<table id="tag_table" border=1>
      <tr>
      <th>Tags</th>
      <th>Delete Tag</th>
      </tr>';

$iter = 0;

$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row) {
    echo "<tr id=" . $iter . "\">";
    echo "<td>" . $row['name'] . "</td>";

    echo "<td>";
    echo "<button id=\"delete\">Delete</button>";

    echo "</td> </tr>";    
}

?>

现在我要做的是在删除按钮中添加.click()功能,但是因为我想使用以下Javascript删除该行而被卡住了:

function deleteTag(btn) {  
  var row = btn.parentNode.parentNode;
  row.parentNode.removeChild(row);
}

但我还需要删除MySQL数据库中的相应条目,需要PHP(我无法在javascript文件中使用)。如果有人对如何完成这些事情有可能的解决方案或想法,我将非常感激。

感谢您的帮助。

编辑1.我的PHP代码:

<?php
  $db = new PDO('my info here bla bla bla');

  $query = "DELETE FROM Tags WHERE name=" . $_POST['name'];

  $db->exec($query);

  $db = null;
?>

1 个答案:

答案 0 :(得分:1)

您可以将按钮标记中的属性onclick=?与JS函数结合使用:onclick=removeTag(this)

<?php

echo "
  <table class="tag_table" border=1>
    <tr>
      <th>Tags</th>
      <th>Delete Tag</th>
    </tr>";

$iter = 0;

$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row)
{
  echo "<tr class=" . $iter . ">";
  echo "<td>" . $row['name'] . "</td>";

  echo "<td>";
  echo "<button onclick=\"deleteTag(this)\" class=\"delete\">Delete</button>";

  echo "</td></tr>";
}

?>

JS:

function deleteTag(btn) {
  // select the row that's concerned
  var row = btn.parentNode.parentNode;

  // select the name of this row
  var name = row.children[0].textContent;

  // remove the row on client side
  row.parentNode.removeChild(row);

  // AJAX call to remove the row server side
  $.ajax({
    url: 'removeRow.php', // this is the target PHP file
    type: "GET",
    data: ({
      name: name
    }),
    success: function(data) {
      // the following will be executed when the request has been completed
      alert('Entry has been deleted successfully!');
    }
  });

}

PHP:诀窍是您需要使用$_REQUEST['...'] 检索AJAX发送的变量,而不是 $_GET['...']$_POST['...']

<?php

if($_REQUEST['name']) {

// if the variable has been successfully received
  $name = $_REQUEST['name'];

  $db = new PDO('my info here bla bla bla');

  $query = $db->prepare("DELETE FROM Tags WHERE name = :name");

  $query->execute(array('name' => $name));

  unset($db, $query)

}