简体   繁体   English

使用ajax删除来自DB的具有动态ID的表行

[英]Delete a table row with dynamic id that comes from DB using ajax

I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax.我有一个表格,它的内容来自数据库。当我点击删除按钮时,我想用 Ajax 删除那一行。 Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .实际上现在它正在工作,但是有一个错误,那就是当我点击按钮时所有的行都被删除,然后如果我刷新,我被删除的行就消失了,其他行会显示出来。但正如我所说,它需要刷新。任何解决方案将不胜感激。

 $('.dashboard-subscribe-form').submit(() => { event.preventDefault(); const currentHiddBtn = $('.dash-subscribe-form-btn'); console.log(currentHiddBtn.closest('tr')); const userCaution = confirm('Want to delete this quote?'); if (userCaution) { //If admin insists to delete the row const deleteId = $('.dash-subscribe-form-btn').attr('value'); $.ajax({ type: "POST", url: "delete-subscribe.php", dataType: "json", data: { deleteId: deleteId }, success: (data) => { if (data.code === '200') { console.log('It works!'); currentHiddBtn.closest('tr').css('background', 'tomato'); currentHiddBtn.closest('tr').fadeOut(1200, () => { }); } else if (data.code === '404') { alert('An error occurred!Please try again.'); } } }); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <tbody> <?php $count = 1; $sqlCommand = "SELECT * FROM `kq0b3_subscribe`"; $sqlCommandPrepare = $pdoObject->prepare($sqlCommand); $sqlCommandPrepare->execute(); while ($result = $sqlCommandPrepare->fetch()) { ?> <tr id="row-<?php echo $result['id']; ?>"> <td class="dashboard-records"> <?php echo $count; ?> </td> <td class="dashboard-records"> <?php echo $result['email']; ?> </td> <td> <form action="" method="post" class="dashboard-subscribe-form"> <input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/> <button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete </button> </form> </td> </tr> <?php $count++; } ?> </tbody>

delete-subscribe.php:删除订阅.php:

<?php
require_once('config.php');

$delete_row = $_POST['deleteId'];


if($delete_row){
    $sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
    $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
    $result = $sqlCommandPrepare->execute([

        $delete_row

    ]);

    /*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
       last line of code) */
    echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
    echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}

UPDATE2: now I'm using : UPDATE2:现在我正在使用:

 $('#row-' + deleteId).css('background', 'tomato');
                    $('#row-' + deleteId).fadeOut(1200, () => {

                    });

but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?但新的问题是:我点击哪个按钮并不重要,第一个行被删除(当点击任何按钮时,在控制台中,第一行按钮的 id 被打印出来,而不是我的实际 id单击。)。我该如何解决这个问题?

I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.我认为在这种情况下,主要问题是使用 CSS 类作为选择器,无论您单击哪个项目,它似乎都在选择第一个实例。

The code causing this is:导致这种情况的代码是:

const deleteId = $('.dash-subscribe-form-btn').attr('value');

You want to be getting the target input from the event object passed from your .submit() .您希望从.submit()传递的event对象中获取目标输入。

I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.我创建了一个jsfiddle,其中包含一个可以适应您的代码的示例,但这里是 jQuery 部分的快速预览。

$('.dashboard-subscribe-form').submit((event) => {
  event.preventDefault()
  console.log(event.target.elements[0]["value"])
  $('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})

It is selecting the first element within the elements array which is the input.它正在选择作为输入的元素数组中的第一个元素。 If you want the button you can use event.target.elements[1]如果你想要按钮,你可以使用event.target.elements[1]

You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest.然后,您还可以使用返回的值删除具有相同 ID 的<tr>而不是查找最近的值。 This could be done in the success part of your ajax call without doing a refresh.这可以在ajax调用的success部分完成,而无需刷新。

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

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