简体   繁体   中英

DataTable not accepting json from database

I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format

    {"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}

which according to a json validator is valid json but when I reload my page I get an error

 "table id=example - Invalid JSON response". 

So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is

<?php
    include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
    <div class="main-wrapper">
        <h2>Home</h2>
        <?php
            if (isset($_SESSION['u_id'])) {
                $sql = "SELECT * FROM employee;";
                $result = mysqli_query($conn,$sql);
                $resultCheck = mysqli_num_rows($result);
                if($resultCheck > 0){
                    echo
                    "<table id='example' class='display' cellspacing='0' width='100%'>
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>ssn</th>
                                    <th>dob</th>
                                    <th>first</th>
                                                    <th>MI</th>
                                                    <th>last</th>
                                </tr>
                            </thead>";
                }
            }
        ?>
    </div>
</section>

<script>

console.log("In the script open");


var editor; // use a global for the submit and return data rendering in the examples

$(document).ready(function() {


        editor = new $.fn.dataTable.Editor( {
            ajax: "infograb.php",
            table: "#example",
            fields: [ {
                    label: "Social#:",
                    name: "ssn"},
                                    {
                    label: "DOB:",
                    name: "dob"},
                                    {label: "First Name:",
                    name: "fn"},
                                    {
                    label: "Middle Initial:",
                    name: "mi"},
                                    {
                    label: "Last Name:",
                    name: "ln"
                        }
            ]
    } );


    $('#example').on( 'click', 'tbody td', function (e) {
        var index = $(this).index();

        if ( index === 1 ) {
            editor.bubble( this, ['fn', 'mi', 'ln'], {
                title: 'Edit name:'
            } );
        }
        else if ( index === 2 ) {
            editor.bubble( this, {
                buttons: false
            } );
        }
        else if ( index === 3 ) {
            editor.bubble( this );
        }

    } );

        var testData = [{
                  "ssn": "98727748",
                  "dob": "2016-02-05",
                  "fn": "jake",
                                    "mi": "a",
                                    "ln": "butler"
                }];

    $('#example').DataTable( {
        dom: "Bfrtip",
        ajax:{
                    url: 'infograb.php',
                    type: 'POST',
                    data: {
                    json: JSON.stringify({ "data": testData })
                    },
                    dataSrc: 'data'
                        },
        columns: [
                        {//sets the checkbox
                            data: null,
                            defaultContent: '',
                            className: 'select-checkbox',
                            orderable: false
                         },
                        { data: "dob" },
            { data: "ssn" },
                        { data: "fn" },
                        { data: "mi" },
                        { data: "ln" },


        ],
        order: [ 1, 'asc' ],
        select: {
            style:    'os',
            selector: 'td:first-child'
        },
        buttons: [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ]
    } );
} );





console.log("End script");


</script>

<?php
    include_once 'footer.php';
?>

and here is the php file that queries the database and returns(allegedly) the json data

<?php
include_once 'dbconn.php';


 $rows = array();

 $sql = "SELECT * FROM employee";
 $result = $conn->query($sql) or die("cannot write");
 while($row = $result->fetch_assoc()){
    $rows[] = $row;
 }

 echo "<pre>";
 print json_encode(array('data'=>$rows));
 echo "</pre>";

 ?>

I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.

Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.

I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:

ajax:{
       url: 'infograb.php',
       type: 'POST',
       data: {
           json: JSON.stringify({ "data": testData })
        },
        dataSrc: 'data'
     },

Should go back to

ajax:{
       url: 'infograb.php',
     },

Remove the pre tags from infograb.php as well as they are unnecessary.

That should load the data into the table for you. You can then start working on the editing side.

Worthwhile Reading and Documentation:

Ajax sourced data

PHP libraries

DataTables Editor 1.7.3 - PHP 5.3+ libraries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM