使用 ajax/datatables 获取数据并在没有 refreshing/reloading 页面的情况下对其进行排序

fetch data and sort it without refreshing/reloading the page using ajax/datatables

问题:我希望每次插入数据并从 sweetalert 弹出窗口中单击确定时,table 会自动获取新插入的数据并且应该已经在 升序。

我尝试过的解决方案: 我尝试过,每次插入成功时,它都会下降到 table 的末尾,这不是 suitable 并且需要重新加载才能排序,我使用 .append() 来获取新数据.

我正在为我的 table 使用 DataTables 插件。

我现在的设置是每次插入数据时我都必须重新加载页面,我认为这不太好,因为我正在使用 ajax。我正在使用 location.href = "URL" 有什么办法可以在不刷新页面的情况下刷新 table 页面吗?

addingUser.js

$(document).ready(function(){
    $('#addStudent').click(function(e){
        e.preventDefault();
        Swal.fire({
            title: "Are you sure?",
            text: "New student will be added added!",
            icon: "success",
            showCancelButton: true,
            allowEscapeKey : false,
            allowOutsideClick: false
        }).then((result) => {
            if (result.isConfirmed) {
                var valid = this.form.checkValidity();
                if(valid){
                    // The studentNumberId should be the basis whether to know if the user is already existing
                    var studentNumberId = $('#studentNumberId').val();
                    var studentFullName = $('#studentFullName').val();
                    var studentPassword = $('#studentPassword').val();
                    var studentEmail = $('#studentEmail').val();
                    var studentYearBlock = $('#studentYearBlock').val();
                        e.preventDefault()
                        $.ajax({
                            type: 'POST',
                            url: 'includes/model_addStudent.php',
                            data: {studentNumberId: studentNumberId,studentFullName: studentFullName,studentPassword: studentPassword,studentEmail: studentEmail,
                                studentYearBlock: studentYearBlock},
                            success: function(data){
                                if(data === "true"){
                                        // swal if the adding failed.
                                    Swal.fire({
                                        title: "Adding Failed",
                                        text: "Student Already Existing",
                                        icon: "warning"
                                    }).then((result) => {
                                        if (result.isConfirmed) {
                                          $('#addModalStudent').modal('hide').find("input").val('');
                                        }
                                      });
                                    }
                                else {
                                    // it fetch without reloading but it adds at the bottom and needs to reload the sort the data. Solution that I tried //

                                    /*
                                    $('#tbl_manageStudents').append(`
                                    <tr>
                                    <td>${studentNumberId}</td>
                                    <td>${studentFullName}</td>
                                    <td>${studentEmail}</td>
                                    <td>${studentYearBlock}</td>
                                    </td>
                                    <td>
                                        <input type="submit" name="viewStudents" id="viewStudents" value="View" class="btn btn-info" 
                                        data-toggle="modal" data-target="#viewExistingStudents<?php echo $row["ID"];?>
                                        <input type="submit" name="deleteRecord" id="deleteRecord" value="Delete" class="btn btn-danger" 
                                        data-toggle="modal" data-target="#deleteSelectedStudent<?php echo $row["ID"];?>
                                    </td>
                                    `);
                                    */
                                    // swal if the user was successfully added
                                    Swal.fire({
                                        title: "Successfully Added!",
                                        text: "New student has been added!",
                                        icon: "success"
                                    }).then((result) => {
                                        if (result.isConfirmed) {
                                            // current set up
                                            location.href = "ManageStudents.php"
                                        $('#addModalStudent').modal('hide').find("input").val('');
                                        // $('#tbl_manageStudents').load("./helper/helper_tblManageStudent.php");

                                        }
                                    });
                                }
                            },
                            error: function(xhr, thrownError, ajaxOptions){
                                Swal.fire({
                                    title: xhr,
                                    text: thrownError,
                                    icon: "info"
                                })
                            } 
                        });
                }
                else {
                    Swal.fire({
                        title: "Error!",
                        text: "Invalid Form",
                        icon: "warning"
                    });
                }
            }
            else {
                Swal.fire(
                'No Changes!',
                'No New Student has been added.',
                'info'
                )
            }
        });   
            });      
    });

ManageUsers.php

<div class="container-sm table-responsive" id="tblManageStudent">
            <table class="table table-striped table-hover table-condense" id="tbl_manageStudents">
                <thead>
                    <tr>
                    <th scope="col">Student ID</th>
                    <th scope="col">Student Name</th>
                    <th scope="col">Student Email</th>
                    <th scope="col">Student Year and Block</th>
                    <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                    <!-- Change the tbl to tbl_students -->
                    <?php 
                        include 'helper/helper_tblManageStudent.php';
                    ?>
                </tbody>
                </table>
            </div>

helper_tblManageStudents.php

<?php
include 'includes/connection_operation.php';
$sql = "SELECT * FROM tbl_students ORDER BY ( 0 + student_id ) ASC";
$query = mysqli_query($conn,$sql);

    if($query)
    {
        while($row = mysqli_fetch_assoc($query))
        {
            ?>
    <td><?php echo $row['student_id']; ?></td>
    <td><?php echo $row['student_name']; ?></td>
    <td><?php echo $row['student_email']; ?></td>
    <td><?php echo $row['student_yrblock']; ?></td>

    <td>
        <input type="submit" name="viewStudents" id="viewStudents" value="View" class="btn btn-info" 
        data-toggle="modal" data-target="#viewExistingStudents<?php echo $row["ID"];?>">
        <input type="submit" name="deleteRecord" id="deleteRecord" value="Delete" class="btn btn-danger" 
        data-toggle="modal" data-target="#deleteSelectedStudent<?php echo $row["ID"];?>">
    </td>
    </tr>
    <?php 
    include './helper/helper_viewExistingStudents.php';
    include './helper/helper_deleteSelectedStudent.php';
        }
    }   
?>

有没有办法在不刷新实际页面的情况下用新插入的数据重新加载helper_tblManageStudents.php的table并获取数据?

我使用数据表 API 通过 ajax 从服务器获取数据并在不重新加载页面的情况下刷新数据。我创建了一个 javascript 方法来处理数据加载并在创建记录后调用此方法。

  1. 在您的视图中像这样创建您的 table
    <table id="dataTable" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Tel</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    
    </tbody>
    </table>
  1. 导入 DataTable files 包括 jquery,创建 js 文件并粘贴此代码
<script type="text/javascript">
$(document).ready(function(){
    function getData(){
        $('#dataTable').DataTable( {
            'processing':true,
            'destroy':true,
            'order': [],
            'ajax': {
                url: "path/users.php",//path to your server file
                type: 'POST'
            },
            lengthChange: true,
            lengthMenu: [
                [ 10, 25, 50, -1 ],
                [ '10 rows', '25 rows', '50 rows', 'Show all' ]
            ]
        });
    }
    getData();
})
</script>
  1. users.php
<?php
    // Create connection to db with server credentials
    $conn = new mysqli($servername, $username, $password);
    
    $sql = "SELECT name, email, tel FROM users ORDER BY id DESC";
    $result = $conn->query($sql);

    $output = array('data' => array());

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {

            $name = htmlentities($row["name"]);
            $email = htmlentities($row["email"]);
            $tel = htmlentities($row["tel"]);
            $status = htmlentities($row["status"]);
            
            //EDITED
            $action = "<button class='btn btn-primary'>View User</button> <button class='btn btn-primary'>Delete User</button>";


            $output['data'][] = array(      
                $name,        
                $email,      
                $tel,
                $action //EDITED
            );
        }
    }

    echo json_encode($output);
    $conn->close();
?>

已编辑:我添加了适合您情况的按钮。您需要做的就是遍历按钮并连接它们。