Предупреждение DataTables: идентификатор таблицы = tablaUsuar ios - Неверный JSON ответ PHP MYSQL - PullRequest
0 голосов
/ 02 мая 2020

Я делаю таблицу записей с DataTables, однако я получаю ошибку, упомянутую выше, она печатает JSON на той же странице, и я уже проверил ее на https://jsonlint.com/, и она говорит мне что JSON правильно, ошибок нет.

Я прилагаю код, который использую, и JSON соответственно

JSON Я получаю

{
"iTotalRecords": "15",
"iTotalDisplayRecords": "15",
"aaData": [
    ["7", "Oscar", "2020-05-20 00:13:26"],
    ["15", "Walter", "2020-06-06 00:13:26"],
    ["5", "Marigel", "2020-05-12 00:11:37"],
    ["13", "Aylin", "2020-06-03 00:13:26"],
    ["1", "Augusto", "2020-05-02 00:09:59"],
    ["3", "Raul", "2020-05-04 00:11:37"],
    ["14", "Wanda", "2020-06-04 00:13:26"],
    ["11", "Abimael", "2020-06-01 00:13:26"],
    ["9", "Julia", "2020-05-28 00:13:26"],
    ["6", "Marco", "2020-05-12 00:13:26"],
    ["12", "Valeria", "2020-06-01 00:13:26"],
    ["4", "Alexis", "2020-05-04 00:11:37"],
    ["8", "Javier", "2020-05-27 00:13:26"],
    ["2", "Larissa", "2020-05-03 00:09:59"],
    ["10", "John", "2020-05-30 00:13:26"]
]
}

HTML

<table id="userTable" class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Date</th>
    </tr>
  </thead>
</table>

JQuery

$(document).ready(function(){
   $("#userTable").DataTable({
      "processing": true,
      "serverSide": true,
      "sAjaxSource": "request.php",
      "columnDefs":[{
         "data":null
      }]
   });
});

PHP (запрос. php)

get("registers_view", "curp", array("folio", "name", "registerDate"));
//Params:
//table name (it's a view) , primary_key , array of fields to display

PHP (Содержание функция get выше)

public function get($table, $index_column, $columns) {
    // Paging
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".intval( $_GET['iDisplayLength'] );
    }

    // Ordering
    $sOrder = "";
    if ( isset( $_GET['iSortCol_0'] ) ) {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
                $sortDir = (strcasecmp($_GET['sSortDir_'.$i], 'ASC') == 0) ? 'ASC' : 'DESC';
                $sOrder .= "`".$columns[ intval( $_GET['iSortCol_'.$i] ) ]."` ". $sortDir .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" ) {
            $sOrder = "";
        }
    }

    $sWhere = "";
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($columns) ; $i++ ) {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" ) {
                $sWhere .= "`".$columns[$i]."` LIKE :search OR ";
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    // Individual column filtering
    for ( $i=0 ; $i<count($columns) ; $i++ ) {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
            if ( $sWhere == "" ) {
                $sWhere = "WHERE ";
            }
            else {
                $sWhere .= " AND ";
            }
            $sWhere .= "`".$columns[$i]."` LIKE :search".$i." ";
        }
    }

    // SQL queries get data to display
    $sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $columns))."` FROM `".$table."` ".$sWhere." ".$sOrder." ".$sLimit;
    $statement = $this->connection->prepare($sQuery);

    // Bind parameters
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
        $statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
    }
    for ( $i=0 ; $i<count($columns) ; $i++ ) {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
            $statement->bindValue(':search'.$i, '%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
        }
    }

    $statement->execute();
    $rResult = $statement->fetchAll();

    $iFilteredTotal = current($this->connection->query('SELECT FOUND_ROWS()')->fetch());

    // Get total number of rows in table
    $sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
    $iTotal = current($this->connection->query($sQuery)->fetch());

    // Output
    $output = array(
        //"sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    // Return array of values
    foreach($rResult as $aRow) {
        $row = array();
        for ( $i = 0; $i < count($columns); $i++ ) {
            if ( $columns[$i] == "version" ) {
                // Special output formatting for 'version' column
                $row[] = ($aRow[ $columns[$i] ]=="0") ? '-' : $aRow[ $columns[$i] ];
            }
            else if ( $columns[$i] != ' ' ) {
                $row[] = $aRow[ $columns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...