【问题标题】:DataTables warning: table id=staff_data - Invalid JSON responseDataTables 警告:表 id=staff_data - 无效的 JSON 响应
【发布时间】:2018-05-09 10:05:42
【问题描述】:

在使用 jquery 和 ajax 以 php 页面形式在表中发布数据方面我还是个新手。当我填写表格时,输入的数据可以保存在我的数据库中,但不幸的是,当我想在我的 php 页面上查看表中的数据时,它一直说 DataTables 警告:表 id=staff_data - 无效的 JSON 响应。有关此错误的更多信息,请参阅http://datatables.net/tn/1。有人可以帮我吗,因为我在另一个表中使用了相同的代码,但只有这个在查看数据时有问题。

staff.php

<?php
//staff.php

include('database_connection.php');

if(!isset($_SESSION['type']))
{
    header('location:login.php');
}

if($_SESSION['type'] != 'master')
{
    header("location:index.php");
}

include('header.php');

?>

    <span id="alert_action"></span>
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="col-lg-10 col-md-10 col-sm-8 col-xs-6">
                        <div class="row">
                            <h3 class="panel-title">Add Staff</h3>
                        </div>
                    </div>
                    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">
                        <div class="row" align="right">
                             <button type="button" name="add" id="add_button" data-toggle="modal" data-target="#staffModal" class="btn btn-success btn-xs">Add</button>
                        </div>
                    </div>
                    <div style="clear:both"></div>
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-sm-12 table-responsive">
                            <table id="staff_data" class="table table-bordered table-striped">
                                <thead><tr>
                                    <th>Staff ID</th>
                                    <th>Staff Name</th>
                                    <th>Staff I/C No</th>
                                    <th>Staff Address</th>
                  <th>Staff Phone No</th>
                  <th>Edit</th>
                                    <th>Delete</th>
                                </tr></thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="staffModal" class="modal fade">
        <div class="modal-dialog">
            <form method="post" id="staff_form">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"><i class="fa fa-plus"></i> Add New Staff</h4>
                    </div>
                    <div class="modal-body">
                        <label>Enter Staff Name</label>
                        <input type="text" name="staff_name" id="staff_name" class="form-control" required />
                    </div>
            <div class="modal-body">
              <label>Enter Staff I/C No</label>
            <input type="number" name="staff_identityno" id="staff_identityno" class="form-control" required />
            </div>
            <div class="modal-body">
              <label>Enter Staff Address</label>
            <input type="text" name="staff_address" id="staff_address" class="form-control" required />
            </div>
            <div class="modal-body">
              <label>Enter Staff Phone No</label>
            <input type="text" name="staff_phoneno" id="staff_phoneno" class="form-control" required />
            </div>
                    <div class="modal-footer">
                        <input type="hidden" name="staff_id" id="staff_id"/>
                        <input type="hidden" name="btn_action" id="btn_action"/>
                        <input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
<script>
$(document).ready(function(){

    $('#add_button').click(function(){
        $('#staff_form')[0].reset();
        $('.modal-title').html("<i class='fa fa-plus'></i> Add New Staff");
        $('#action').val('Add');
        $('#btn_action').val('Add');
    });

    $(document).on('submit','#staff_form', function(event){
        event.preventDefault();
        $('#action').attr('disabled','disabled');
        var form_data = $(this).serialize();
        $.ajax({
            url:"staff_action.php",
            method:"POST",
            data:form_data,
            success:function(data)
            {
                $('#staff_form')[0].reset();
                $('#staffModal').modal('hide');
                $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
                $('#action').attr('disabled', false);
                staffdataTable.ajax.reload();
            }
        })
    });

    $(document).on('click', '.update', function(){
        var staff_id = $(this).attr("id");
        var btn_action = 'fetch_single';
        $.ajax({
            url:"staff_action.php",
            method:"POST",
            data:{staff_id:staff_id, btn_action:btn_action},
            dataType:"json",
            success:function(data)
            {
                $('#staffModal').modal('show');
                $('#staff_name').val(data.staff_name);
                $('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Staff Information");
                $('#staff_id').val(staff_id);
                $('#action').val('Edit');
                $('#btn_action').val("Edit");
            }
        })
    });

    var staffdataTable = $('#staff_data').DataTable({
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"staff_fetch.php",
            type:"POST"
        },
        "columnDefs":[
            {
                "targets":[0,5, 6],
                "orderable":false,
            },
        ],
        "pageLength": 25
    });
    $(document).on('click', '.delete', function(){
        var staff_id = $(this).attr('id');
        var status = $(this).data("status");
        var btn_action = 'delete';
        if(confirm("Are you sure you want to change status?"))
        {
            $.ajax({
                url:"staff_action.php",
                method:"POST",
                data:{staff_id:staff_id, status:status, btn_action:btn_action},
                success:function(data)
                {
                    $('#alert_action').fadeIn().html('<div class="alert alert-info">'+data+'</div>');
                    staffdataTable.ajax.reload();
                }
            })
        }
        else
        {
            return false;
        }
    });
});
</script>

<?php
include('footer.php');
?>

staff_fetch.php

    <?php

//staff_fetch.php

include('database_connection.php');

$query = '';

$output = array();

$query .= "SELECT * FROM staff ";

if(isset($_POST["search"]["value"]))
{
    $query .= 'WHERE staff_name LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR staff_id LIKE "%'.$_POST["search"]["value"].'%" ';
  $query .= 'OR staff_phoneno LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR staff_identityno LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR staff_address LIKE "%'.$_POST["search"]["value"].'%" ';
}

if(isset($_POST['order']))
{
    $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY staff_id DESC ';
}

if($_POST['length'] != -1)
{
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$data = array();

$filtered_rows = $statement->rowCount();

foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row['staff_id'];
    $sub_array[] = $row['staff_name'];
  $sub_array[] = $row['staff_identityno'];
    $sub_array[] = $row['staff_address'];
  $sub_array[] = $row['staff_phoneno'];
    $sub_array[] = '<button type="button" name="update" id="'.$row["staff_id"].'" class="btn btn-warning btn-xs update">Update</button>';
    $sub_array[] = '<button type="button" name="delete" id="'.$row["staff_id"].'" class="btn btn-danger btn-xs delete" data-status="'.$row["category_status"].'">Delete</button>';
    $data[] = $sub_array;
}

$output = array(
    "draw"          =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records($connect),
    "data"              =>  $data
);


function get_total_all_records($connect)
{
    $statement = $connect->prepare("SELECT * FROM staff");
    $statement->execute();
    return $statement->rowCount();
}
echo json_encode($output);

?>

staff_action.php

<?php

//staff_action.php

include('database_connection.php');

if(isset($_POST['btn_action']))
{
    if($_POST['btn_action'] == 'Add')
    {
        $query = "
        INSERT INTO staff (staff_name, staff_identityno, staff_address, staff_phoneno)
        VALUES (:staff_name, :staff_identityno, :staff_address, :staff_phoneno)
        ";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':staff_name'   =>  $_POST["staff_name"],
        ':staff_identityno' =>  $_POST["staff_identityno"],
        ':staff_address'    =>  $_POST["staff_address"],
          ':staff_phoneno'  =>  $_POST["staff_phoneno"]
            )
        );
        $result = $statement->fetchAll();
        if(isset($result))
        {
            echo 'New Staff Added';
        }
    }



    if($_POST['btn_action'] == 'fetch_single')
    {
        $query = "SELECT * FROM staff WHERE staff_id = :staff_id";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':staff_id' =>  $_POST["staff_id"]
            )
        );
        $result = $statement->fetchAll();
        foreach($result as $row)
        {

      $output['staff_name'] =   $row["staff_name"];
      $output['staff_identityno']   =   $row["staff_identityno"];
      $output['staff_address']  =   $row["staff_address"];
      $output['staff_phoneno']  =   $row["staff_phoneno"];
        }
        echo json_encode($output);
    }

    if($_POST['btn_action'] == 'Edit')
    {
        $query = "
        UPDATE staff SET
        staff_address = '".$_POST["staff_address"]."',
        staff_phoneno = '".$_POST["staff_phoneno"]."'
        WHERE staff_id = '".$_POST["staff_id"]."'
        ";
        $statement = $connect->prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        if(isset($result))
        {
            echo 'Staff Information Edited';
        }
    }

}

?>

【问题讨论】:

    标签: php jquery ajax datatables


    【解决方案1】:

    您在每次循环迭代中多次错误地递增 $sub_array 索引,从而错误地设置了 $data 的值。

    在 staff_fetch.php 中用这个替换你的 foreach 循环:

    $sub_array = array();
    foreach($result as $row)
    {
        $edit = '<button type="button" name="update" id="'.$row["staff_id"].'" class="btn btn-warning btn-xs update">Update</button>';
        $delete = '<button type="button" name="delete" id="'.$row["staff_id"].'" class="btn btn-danger btn-xs delete" data-status="'.$row["category_status"].'">Delete</button>'; 
    
        $sub_array[] = array(
            $row['staff_id'],
            $row['staff_name'],
            $row['staff_identityno'],
            $row['staff_address'],
            $row['staff_phoneno'],
            $edit,
            $delete
        );
    
    }
    $data = $sub_array;
    

    【讨论】:

    • 更新了我的答案。
    • 我尝试用你的代码替换我的代码,但仍然出现警告。我的其他表我使用与此完全相同的代码,但没有问题,例如警告数据表无效 json 响应发生:(
    • 我在本地测试过,效果很好。你能把staff_fetch.php -> error_reporting(0); 放在最上面吗?
    • 放在最上面是什么意思?抱歉,我还是新手,不太明白我现在在做什么啊哈哈
    • 你好!非常感谢您可以完全按照我的意愿查看表格!谢谢
    猜你喜欢
    • 2014-11-04
    • 2018-10-31
    • 2015-04-20
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2016-02-08
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多