服务器端表使用JS,Php或Ajax从表(而不是数据库)中删除行

时间:2018-08-20 02:49:01

标签: javascript php ajax datatable

项目链接:https://databasetable-net.000webhostapp.com/

下面的代码正确删除了表中的一行:

  $('#example').on('click', '.delete_btn', function () {
      var row = $(this).closest('tr');
      var data = table.row( row ).data().delete;
      console.log(data);
      alert("delete_btn clicked");
      row.remove();
    });

但是,它并没有彻底删除该行。如果刷新页面,则被“删除”的行仍然存在。我相信这是因为我没有从数据库中删除该行。通常在php中,您可以使用以下类似的方法安全地删除数据库中的一行:

id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1"); 
$stmt->bind_param('i', $id);
$stmt->execute(); 
$stmt->close();
header('location: index.php');

编辑:修订的代码Index.php:

  (document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},

//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});

$(function(){
    $(document).on('click','.delete_btn',function(){

        var del_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  //removed the "$" from the ele variable. It's a js variable.
        console.log(del_id);

        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: { 'del_id' : del_id}, 

            success: function(data){ //data is an json encoded array.

              console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.

              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
                alert("delete btn clicked");
                ele.remove();
              }else{
                console.log('The row was not deleted.');
                }

             }

            });
        });
}); //http://jsfiddle.net/zfohLL0a/

}); //end doc ready

delete.php代码:

$del_id = $_POST['del_id']; 
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();

$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
  $array['success'] = TRUE;
}

echo json_encode($array);
?>

部分解决方案: Sample format how to setup the ajax. 您必须首先使用datatables.net“ ajax”:原始server.php的方法。但是之后,您对add.php,delete.php等使用常规的$ .ajax方法。这令人困惑,因为对ajax使用了两种不同的语法。最简单的方法就是查看示例链接。 Youtube video for same code

另一个讨论与ajax / json之间发送信息的有用链接是one two three Four

2 个答案:

答案 0 :(得分:1)

使用最新更新的代码更新了答案。

JS

$(function(){
    $(document).on('click','.delete_btn',function(){

        var del_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  //removed the "$" from the ele variable. It's a js variable.
        console.log(del_id);

        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: {  //Set up your post data as an array of key value pairs.

              'del_id' : del_id

            }, 

            success: function(data){ //data is an json encoded array.

              console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.

              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
                ele.fadeOut().remove();
              }else{
                console.log('The row was not deleted.');
                }

             }

            });
        });
});

delete.php

$del_id = $_POST['del_id']; 
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();

$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
  $array['success'] = TRUE;
}

echo json_encode($array); //Your ajax is setup to expect a json response.  
//json_encode the $array and echo it out.  You have to do this.  
//When you "echo" out a value, that is what the server is going to submit back to the ajax function.
//If you do not do this, the ajax script will not recieve a response from the delete.php page.

此代码应为您工作。

答案 1 :(得分:0)

除了Joesph的回复外,他的帮助非常大:

“控制台显示“ Uncaught RangeError:超出最大调用堆栈大小”。看起来好像没有发出Ajax调用(“网络”选项卡上什么都没有显示)-创建请求时必须是这样。怀疑我可能需要JSON.stringify您的del_id。“

有人建议这样做: “主要的堆栈问题是由var edit_id = $(this).closest('tr');引起的。您尝试将整个jQuery对象作为数据发送到ajax中。然后jQuery无法在内部对其进行序列化并抛出适合的结果

您可能希望发送该行中的某些属性(例如ID或数据属性)(不清楚期望值是什么。”

如果有任何建议,请发表。我将尽快编辑任何最终的代码解决方案。