使用 PHP 和 Ajax 创建动态 Table 以将数据插入 table,如果不在视图或第一页内则无法使用按钮

Creating Dynamic Table using PHP and Ajax to insert data into table, unable to use buttons if not within view or first page

开门见山:

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

<?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
  }
}
?>

table 的工作方式与我预期的输出和显示完全一致。虽然编辑和删除按钮仅在第一页上有效,但在用户显示第二页和之后的任何页面后,“工具”按钮将不存在。

GIF Displaying Page 2 edit/delete not working

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

这适用于我所有的 table。如果 table 不完全可见,则按钮 (edit/delete) 也不起作用。我不确定按钮与 table 或 sweetalert 交互的方式。

不可见 Not Visible

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

<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 时遇到这个问题吗? 这是数据 table 中的故障还是我这边的错误,因为没有包含任何内容来处理下一页或按钮不可见?

我尝试过的: - 重新设计整个 table(没用) - 更改了所有 jquery 和 ajax 调用(简化但仍然无效)

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

感谢您花时间阅读并帮助我评估情况,因为这是第一次发生这种情况。 datatables.

以前从未发生过

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

而不是:

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

尝试:

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

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

在此处查看文档:https://api.jquery.com/on/