Jquery 使用ajax/datatables获取数据并对其排序,而无需刷新/重新加载页面
问题:我希望每次插入数据并从sweetalert弹出窗口单击OK时,表都会自动获取新插入的数据,并且应该已经在中进行了排序 升序 我尝试的解决方案: 我尝试过,每次成功插入时,它都会进入表的末尾,这不合适,需要重新加载以进行排序,我使用.append()获取新数据 我正在为我的表使用DataTables插件 我目前的设置是每次插入数据时都必须重新加载页面,我认为这不好,因为我使用的是ajax。我使用的是Jquery 使用ajax/datatables获取数据并对其排序,而无需刷新/重新加载页面,jquery,ajax,datatables,sweetalert2,Jquery,Ajax,Datatables,Sweetalert2,问题:我希望每次插入数据并从sweetalert弹出窗口单击OK时,表都会自动获取新插入的数据,并且应该已经在中进行了排序 升序 我尝试的解决方案: 我尝试过,每次成功插入时,它都会进入表的末尾,这不合适,需要重新加载以进行排序,我使用.append()获取新数据 我正在为我的表使用DataTables插件 我目前的设置是每次插入数据时都必须重新加载页面,我认为这不好,因为我使用的是ajax。我使用的是location.href=“URL” 有没有办法在不刷新页面的情况下刷新页面中的表 addi
location.href=“URL”
有没有办法在不刷新页面的情况下刷新页面中的表
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'
)
}
});
});
});
$(文档).ready(函数(){
$(“#添加学生”)。单击(函数(e){
e、 预防默认值();
喷火({
标题:“你确定吗?”,
文本:“将添加新学生!”,
图标:“成功”,
showCancelButton:true,
allowEscapeKey:false,
allowOutsideClick:false
})。然后((结果)=>{
如果(结果已确认){
var valid=this.form.checkValidity();
如果(有效){
//studentNumberId应该是是否知道用户是否已经存在的基础
var studentNumberId=$('#studentNumberId').val();
var studentFullName=$('#studentFullName').val();
var studentPassword=$('#studentPassword').val();
var studentEmail=$('#studentEmail').val();
var studentYearBlock=$('#studentYearBlock').val();
e、 预防默认值()
$.ajax({
键入:“POST”,
url:'includes/model_addStudent.php',
数据:{studentNumberId:studentNumberId,studentFullName:studentFullName,studentPassword:studentPassword,studentEmail:studentEmail,
studentYearBlock:studentYearBlock},
成功:功能(数据){
如果(数据==“真”){
//如果添加失败,则swal。
喷火({
标题:“添加失败”,
文本:“学生已存在”,
图标:“警告”
})。然后((结果)=>{
如果(结果已确认){
$('addModalStudent').modal('hide').find(“input”).val('');
}
});
}
否则{
//它不需要重新加载就可以获取数据,但是它在底部添加了数据,并且需要重新加载排序数据//
/*
$('tbl#u manageStudents')。追加(`
${studentNumberId}
${studentFullName}
${studentEmail}
${studentYearBlock}
我使用dataTables API通过ajax从服务器获取数据,并在不重新加载页面的情况下刷新数据
在视图中,按如下方式创建表
名称
电子邮件
电话
行动
导入包含jquery的文件,创建js文件并粘贴此代码
$(文档).ready(函数(){
函数getData(){
$('#dataTable')。dataTable({
“处理”:正确,
"摧毁":对,,
“订单”:[],
“ajax”:{
url:“path/users.php”,//服务器文件的路径
类型:“POST”
},
长度变化:对,
长度菜单:[
[ 10, 25, 50, -1 ],
[“10行”、“25行”、“50行”、“全部显示”]
]
});
}
getData();
})
users.php
编辑:我已经添加了按钮以适合您的情况。您所需要做的就是在按钮上循环并对其进行处理。方法是错误的。使用Datatable api将新数据传递给插件,然后重新绘制。如果您插入自己的html,则行html的插件缓存和数据对它一无所知,我想问一下,因为用户.php现在已转换为json,我正在尝试循环按钮,我也尝试将其放入while循环中,但它给了我错误,给了我无效的json响应。谢谢。
<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>
<?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';
}
}
?>
<table id="dataTable" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Tel</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<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>
<?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();
?>