【问题标题】:fetch data and sort it without refreshing/reloading the page using ajax/datatables获取数据并对其进行排序,而无需使用 ajax/datatables 刷新/重新加载页面
【发布时间】:2021-06-26 17:03:55
【问题描述】:

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

我尝试过的解决方案: 我试过每次成功插入时都会走到表的末尾,这是不合适的,需要重新加载才能排序,我使用 .append() 来获取新数据。

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

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

添加用户.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的表而不刷新实际页面并获取数据?

【问题讨论】:

  • 方法错误。使用 Datatable api 将新数据传递给插件,然后进行重绘。如果您插入自己的 html,则行 html 和数据的插件缓存对此一无所知

标签: jquery ajax datatables sweetalert2


【解决方案1】:

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

  1. 在您的视图中像这样创建您的表格
    <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();
?>

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

【讨论】:

  • 您好,我想问一下,因为 users.php 现在已经转换为 json,我正在尝试循环按钮以及我尝试将其放入 while 循环但它给我错误它给我一个无效的 json 响应。谢谢。
猜你喜欢
  • 2017-12-24
  • 2012-06-12
  • 2013-05-28
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 2017-10-06
  • 1970-01-01
相关资源
最近更新 更多