首页 > 解决方案 > 使用 PHP 和 Ajax 创建动态表以将数据插入表中,如果不在视图或第一页中,则无法使用按钮

问题描述

让我们直奔主题:

我使用数据库中的动态数据创建了一个数据表。我使用 php 调用数据并将其插入到表中。

<?php
$getAttendance = $functions->runSQL("dynamic data sql query ");
$getAttendance->execute();
$attendance = $getAttendance->fetchAll(PDO::FETCH_ASSOC);

foreach ($attendance as $key => $data) {
  $getEmployeeName = $functions->runSQL("another sql query to call firstname and last name");
  $getEmployeeName->execute() ;
  $employeeName = $getEmployeeName->fetchAll(PDO::FETCH_ASSOC);
  foreach ($employeeName as $key => $name) {
?>
                  <tr>
                    <td><?= $data['date']; ?></td>
                    <td><?= $data['employee_id']; ?></td>
                    <td><?= $name['firstname'] . " " . $name['lastname']; ?></td>
                    <td><?= $data['clock_in']; ?></td>
                    <td><?= $data['clock_out']; ?></td>
                    <td>
                      <button class="btn btn-warning editAttendance" id="editAttendance-<?= $data['id']; ?>"  data-id="<?= $data['id']; ?>"><i class="fa fa-edit"></i>&nbsp;EDIT</button>
                      <button class="btn btn-danger deleteAttendance" id="deleteAttendance-<?= $data['id']; ?>" data-id="<?= $data['id']; ?>"><i class="fa fa-trash"></i>&nbsp;DELETE</button>  
                    </td>
                  </tr>

<?php
  }
}
?>

该表的工作方式与我期望它的输出和显示方式完全相同。尽管编辑和删除按钮仅在第一页上有效,但在用户显示第二页和之后的任何页面后,“工具”按钮将不存在。

GIF 显示第 2 页编辑/删除不起作用

正如您在上面的 GIF 中看到的,编辑和删除功能可以正常工作,直到加载分页的第二页。

这适用于我所有的桌子。如果表格不完全可见,按钮(编辑/删除)也不起作用。我不确定它是按钮与桌子交互的方式还是sweetalert。

不可见 不可见

可见但无法工作或与 sweetalert 和 ajax 编辑或删除调用交互(两者都如第一个 GIF 所示) 可见

<script>

$(document).ready(function(e) {
  $('[id^=editAttendance]').on('click', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    swal.showLoading();
    $.ajax({
        type: "POST",
        url: "<?= $site->baseURL; ?>/",
        dataType: "json",
        data: { id: id},
        success: function(response) {
            Swal.fire({
                title: "<div style='color:orange;'>Update Attendance</div>",
                html: "<div><label>Date</label>&nbsp;<input class='form-control' type='date' value='" + response[0]['date'] + "' id='attendanceDate'  placeholder=" + response[0]['date'] + " /></div><br />" +
            "<div><label>Clock In</label>&nbsp;<input class='form-control' id='attendanceClockIn' type='time' value='" + response[0]['clock_in'] + "'  placeholder='" + response[0]['clock_in'] + "' /></div><br />" +
            "<div><label>Clock Out</label>&nbsp;<input class='form-control' id='attendanceClockOut' type='time' value='" + response[0]['clock_out'] + "'  placeholder='" + response[0]['clock_out'] + "' /></div><br />",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'YES, EDIT IT!',
                cancelButtonText: 'CANCEL'
              }).then((result) => {
                if (result.isConfirmed) {

                    var attendanceDate = $('#attendanceDate').val();
                    var attendanceClockIn = $('#attendanceClockIn').val();
                    var attendanceClockOut = $('#attendanceClockOut').val();
                    if ( attendanceDate == "" || attendanceClockIn  == "" || attendanceClockOut  == "") {
                      Swal.fire({
                        icon: 'error',
                        text: 'please enter a value in either inputs'
                        });
                    } else {
                      Swal.fire({
                        title: "<div style='color:red;'>Are You Sure ?</div>",
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'YES!',
                        cancelButtonText: 'CLOSE'
                      }).then((result) => {
                        if (result.isConfirmed) {
                            $.ajax({
                              type: "POST",
                              url: "<?= $site->baseURL; ?>/",
                              dataType: "json",
                              data: {
                                  id:id,
                                  dates: attendanceDate,
                                  clockIn: attendanceClockIn,
                                  clockOut: attendanceClockOut 
                              },
                              success: function(data) {
                                 Swal.fire({
                                    icon: data.success,
                                    title: 'Attendance Edited!',
                                    confirmButtonColor: '#28a745',
                                    confirmButtonText: 'CLOSE!',
                                    text: 'Click CLOSE to continue.',
                                  }).then((result) => {
                                    if (result.isConfirmed) {
                                      location.reload();
                                    }
                                 });
                              },
                              error: function(data) {
                                console.log(data);
                              }
                            });

                            
                        }
                      });
                    }

                    
                }
              });
        },
        error: function (response) {
            swal.fire(
            "Internal Error",
            "Oops, Something Happened, contact webmaster", // had a missing comma
            "error"
            );
        }
    });
  });

    $('[id^=deleteAttendance]').on('click', function(e) {
        e.preventDefault();
        var id = $(this).data('id');
            $.ajax({
                type: "POST",
                url: "<?= $site->baseURL; ?>/",
                dataType: "json",
                data: { id:id },
                success: function(data) {
                  Swal.fire({
                    title: "<div style='color:red;'>Delete Attendance</div>",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'YES!',
                    cancelButtonText: 'CLOSE',
                    html: "<strong>You are about to remove <h4 style='color:red;'>" + data[0]['employee_id'] + " :: " + data[0]['date'] + " : " + data[0]['clock_in'] + "</h4></strong>"
                  }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                          type: "POST",
                          url: "<?= $site->baseURL; ?>/",
                          dataType: "json",
                          data: {id: id},
                          success: function(data){
                              Swal.fire({
                                  icon: data.success,
                                  title: 'Attendance Deleted!',
                                  confirmButtonColor: '#28a745',
                                  confirmButtonText: 'CLOSE!',
                                  text: 'Click CLOSE to continue.'
                                }).then((result) => {
                                  if (result.isConfirmed) {
                                    location.reload();
                                  }
                               });
                          },
                          error: function(data){
                            swal.fire(
                            "Internal Error",
                            "Oops, Something Happened, contact webmaster.", // had a missing comma
                            "error"
                            );
                          }
                        });
                    }
                  }); 

              },
              error: function(data){
                console.log(data);
              }
            });
    });

    
    $('#add-new-attendance').on('click', function(e) {
    
        e.preventDefault();
        Swal.fire({
                title: "<div style='color:green;'>Add Attendance</div>",
                html: "<div><label>Employee ID</label>&nbsp;<input class='form-control' type='text'  id='attendanceEmployeeID'  placeholder='EG: FSJXXXX' required autofocus /></div><br />" +
            "<div><label>Date</label>&nbsp;<input class='form-control' id='attendanceDate' type='date'  placeholder='100' required /></div><br />" +
            "<div><label>Clock In</label>&nbsp;<input class='form-control' id='attendanceClockIn' type='time'  placeholder='100' required /></div><br />" +
            "<div><label>Clock Out</label>&nbsp;<input class='form-control' id='attendanceClockOut' type='time'  placeholder='100' required /></div><br />",
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'YES, ADD IT!',
                cancelButtonText: 'CANCEL'
              }).then((result) => {

                if (result.isConfirmed) {
                    var description = $('#deductionDescription').val();
                    var amount = $('#deductionAmount').val();
                    if (description == "" || amount == "") {
                      Swal.fire({
                        icon: 'error',
                        text: 'please enter a value in either inputs'
                        });
                    } else {
                            $.ajax({
                              type: "POST",
                              url: "<?= $site->baseURL; ?>/",
                              dataType: "json",
                              data: {
                                  description: description,
                                  amount: amount
                              },
                              success: function(data) {
                                 Swal.fire({
                                    icon: data.success,
                                    title: 'Deduction Added!',
                                    confirmButtonColor: '#28a745',
                                    confirmButtonText: 'CLOSE!',
                                    text: 'Click CLOSE to continue.',
                                  }).then((result) => {
                                    if (result.isConfirmed) {
                                      location.reload();
                                    }
                                 });
                              },
                              error: function(data) {
                                console.log(data);
                              }
                            });
                    }
                }

              });
    });

});
</script>

其他人使用 datatables js 有这个问题吗?这是数据表中的故障还是我这边的错误,因为没有包含任何处理下一页的内容或按钮不可见?

我尝试过的: - 重新设计整个表(不起作用) - 更改了所有 jquery 和 ajax 调用(简化但仍然不起作用)

什么工作: - 显示没有分页的完整表格似乎解决了这个问题。尽管加载 100 个页面并将它们显示在一个页面中是不明智的(不能用作修复)。

感谢您花时间阅读并帮助我评估情况,因为这是第一次发生这种情况。数据表以前从未发生过。

标签: phpjqueryajaxdatatablessweetalert2

解决方案


您应该用选择器过滤的主体上的单击侦听器替换每个 jQuery 单击事件侦听器。

代替:

$('[id^=editAttendance]').on('click', function(e) {...});

尝试:

$('body').on('click', '[id^=editAttendance]', function(e) {...});

通过这种方式,它也适用于在页面初始呈现后附加到 DOM 的按钮。

有关文档,请参见此处:https ://api.jquery.com/on/


推荐阅读