DataTables警告:table id = staff_data - 无效的JSON响应

时间:2018-05-09 10:05:42

标签: php jquery ajax datatables

我仍然使用jquery和ajax以php页面形式在表格中发布数据。当我填写表格时,输入的数据可以保存在我的数据库中,但不幸的是,当我想在我的php页面中查看表格中的数据时,它会继续说DataTables警告:table 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';
        }
    }

}

?>

1 个答案:

答案 0 :(得分:0)

您通过在每次循环迭代中多次错误地递增$ sub_array索引来错误地设置$ data的值。

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

cached_users