我怎么能用jquery做对话框

时间:2015-09-04 03:26:10

标签: php jquery ajax

我想通过显示确认消息的php表单删除记录,当您选择接受时,删除记录并向我发送成功操作的消息。但没有刷新页面

1 个答案:

答案 0 :(得分:0)

你需要通过使用Ajax来做到这一点,在这里我给你演示如何实现它的示例。但是以table为例(因为我们不知道你的HTML结构),但很容易实现并知道它是如何工作的。这个概念仍然相同。

此处 HTML 结构

<table>
<tr>
    <th>Name</th>
    <th>Operation</th>
</tr>
<tr>
    <td>John</td>
    <td> <a href="#" data-id="1" class="btnDelete">delete</a>

    </td>
</tr>
<tr>
    <td>Johny</td>
    <td> <a href="#" data-id="2" class="btnDelete">delete</a>

    </td>
</tr>
<tr>
    <td>John WHo</td>
    <td> <a href="#" data-id="3" class="btnDelete">delete</a>

    </td>
</tr>
</table>

注意我使用data-id来存储唯一的数据ID。在您的情况下,放入您的表单并使用任何匹配的jQuery选择器获取它的值。以下是JS代码:

$(document).on('click', '.btnDelete', function (e) {
  e.preventDefault();
  var id = $(this).data('id');
  var $this = $(this);

  alert('My data id is ' + id);
  // find any dialog box available out there
  // using confirm box to choose either cancel or ok
  // if Ok was clicked, execute this below code
  if ( confirm('Are you sure to delete this data???') ){
    $.ajax({
        type: 'POST', // method used
        data: {
            id: id // send into php process page
        },
        url: 'serverSideProcessToDelete.php', // php process page
        success: function (data) {
            // data should be have 1 or 2 values in it
            // on success operation
            // remove DOM element from page
            // DO YOUR LOGIC HERE
            if ( +data == 1) {
                // remove dom element
                // if you're using form, try to figure out 
                // top level parent for removing part
                $this.closest('tr').remove();
                alert('Success Delete Data');
            } else {
                alert('Failed Delete Data');
            }

        }
    });
  }
});

这里 PHP (serverSideProcessToDelete.php)代码:

<?php
// connection things
$con = ......
// retrieved the data send from ajax
$id = $_POST['id'];
// do delete operation
$del = mysqli_query($con, "DELETE FROM user WHERE id = '$id'");
if ( $del ) {
  // send back to Ajax success callback
  // success
  $flag = 1;
} else {
  // send back to Ajax success callback
  // error delete
  $flag = 2;
}
echo $flag;
?>

This插件非常酷,可用于留言通知。 将这些代码调整到您的要求中。祝你有愉快的一天!