How to populate a jquery datatable using server side processing (PHP)?

[亡魂溺海] 提交于 2019-12-12 05:57:34

问题


I'm trying to populate a datatable with a server side PHP script which echoes the data from a postgres table (~75K rows). I followed the steps given in the datatable page and implemented it, but the table doesn't show any data. This is what I have so long:

table definition in a jsp file:

<table id="myTable" class="table table-striped" width="100%">
                            <thead>
                                <tr>
                                    <th>idpersona</th>
                                    <th>primerapellido</th>
                                    <th>primernombre</th>
                                    <th>numeroidentificacion</th>
                                    <th>fechanacimiento</th>
                                </tr>
                            </thead>
                            <tfoot>
                                <tr>
                                    <th>idpersona</th>
                                    <th>primerapellido</th>
                                    <th>primernombre</th>
                                    <th>numeroidentificacion</th>
                                    <th>fechanacimiento</th>
                                </tr>
                            </tfoot>
                        </table>

Here is my function to initialise the table. I tried for hours (I'm a newbie programmer) to find the right folder where I must place the PHP file. Right now it is in the htdocs folder of my apache server (so I can access it from /localhost/tablabd.php). Is this the right way to do it?

<script type="text/javascript" language="javascript" class="init">
    $(document).ready(function() {
        $('#myTable').dataTable( {
            "Processing": true,
            "ServerSide": true,
            "sAjaxSource": "http://localhost/tablabd.php"
        } );
    } );
    </script>

And finally the PHP script. When I type localhost/tablabd.php in my browser, all the data is fetched correctly. But when I execute my Java project, it doesn't show anything in the table 'myTable'.

<?php
    /*
     * Script:    DataTables server-side script for PHP and PostgreSQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array("idpersona", "primerapellido","primernombre", "numeroidentificacion", "fechanacimiento");

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = '"idpersona"';

    /* DB table to use */
    $sTable = '"tpersonas"';

    /* Database connection information */
    $gaSql['user']       = "postgres";
    $gaSql['password']   = "******";
    $gaSql['db']         = "sisben";
    $gaSql['server']     = "localhost";



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * DB connection
     */
    $gaSql['link'] = pg_connect(
        " host=".$gaSql['server'].
        " dbname=".$gaSql['db'].
        " user=".$gaSql['user'].
        " password=".$gaSql['password']
    ) or die('Could not connect: ' . pg_last_error());


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] )." OFFSET ".
            intval( $_GET['iDisplayLength'] );
    }


    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
            }
        }

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


    /*
     * Filtering
     * NOTE This assumes that the field that is being searched on is a string typed field (ie. one
     * on which ILIKE can be used). Boolean fields etc will need a modification here.
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $_GET['bSearchable_'.$i] == "true" )
            {
                $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ")";
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
        }
    }


    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());

    $sQuery = "
        SELECT $sIndexColumn
        FROM   $sTable
    ";
    $rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
    $iTotal = pg_num_rows($rResultTotal);
    pg_free_result( $rResultTotal );

    if ( $sWhere != "" )
    {
        $sQuery = "
            SELECT $sIndexColumn
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
        $iFilteredTotal = pg_num_rows($rResultFilterTotal);
        pg_free_result( $rResultFilterTotal );
    }
    else
    {
        $iFilteredTotal = $iTotal;
    }



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

    while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
    {
        $row = array();

        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == 'idpersona' )
            {
                /* Special output formatting for 'ID' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];

            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );

    // Free resultset
    pg_free_result( $rResult );

    // Closing connection
    pg_close( $gaSql['link'] );
?>

and a sample of the output of the script in the broswer: maybe I'm missing a column mapping somewhere?

{"sEcho":0,"iTotalRecords":74047,"iTotalDisplayRecords":74047,"aaData":[["e71657b3-a7f5-4a10-bc43-d0edbeb5cdab","PEREZ","ABDON","4299249","1947-07-10 00:00:00"],["796db2d4-fee3-4cca-ae06-429a2ea6c5af","TORREZ","MARIA","24240762","1951-09-17 00:00:00"]]}

Here is the info Firebug shows when I access the page on my application which contains the table:

_   1440905636814
columns[0][data]    0
columns[0][name]    
columns[0][orderable]   true
columns[0][search][regex]   false
columns[0][search][value]   
columns[0][searchable]  true
columns[1][data]    1
columns[1][name]    
columns[1][orderable]   true
columns[1][search][regex]   false
columns[1][search][value]   
columns[1][searchable]  true
columns[2][data]    2
columns[2][name]    
columns[2][orderable]   true
columns[2][search][regex]   false
columns[2][search][value]   
columns[2][searchable]  true
columns[3][data]    3
columns[3][name]    
columns[3][orderable]   true
columns[3][search][regex]   false
columns[3][search][value]   
columns[3][searchable]  true
columns[4][data]    4
columns[4][name]    
columns[4][orderable]   true
columns[4][search][regex]   false
columns[4][search][value]   
columns[4][searchable]  true
draw    1
length  20
order[0][column]    0
order[0][dir]   asc
search[regex]   false
search[value]   
start   0

Thanks in advance.


回答1:


SOLUTION

Correct option names are bProcessing and bServerSide. Your DataTables initialization code should be:

$('#myTable').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "/tablabd.php"
});

NOTES

I have changed URL to /tablabd.php because if your HTML and PHP are on different domain, Ajax calls may fail unless you allow cross-domain requests. Make sure you have HTML and PHP on the same domain.



来源:https://stackoverflow.com/questions/32281489/how-to-populate-a-jquery-datatable-using-server-side-processing-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!