将$ _request值传递给Datatable Ajax脚本

时间:2015-03-24 19:44:38

标签: php jquery datatables

我正在使用DataTables,并希望将REQUEST值传递给php脚本。 Firebug报告未定义的索引。 这是PHP脚本:

  $sIndexColumn = "opportunity_acccount_id";
  $sTable = "opportunities_base";
  $sWhere = "opportunity_acccount_id = '$_REQUEST['account_id']'";

这是初始化表格的JavaScript:

 var oTable = $('#opportunities_table').dataTable( {
              // "aoColumnDefs": [
              //     { "bSortable": false, "aTargets": [ 0 ] }
              // ],
            "aaSorting": [[0, 'asc']],
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "../includes/functions/opportunity_json.php",
            "fnServerParams": function ( aoData ) {
                        aoData.push( { "name": "acct_id", "value": "3" } );
                      },

                    "aoColumns": [
            { "mData": "0" },
            { "mData": "2" },
            //Begin actual rows
            { "mData": "6" },
            { "mData": "10" },
            { "mData": "12" },
            { "mData": "8" },
            { "mData": "4" },
          ],
          "sDom": '<"dt-panelmenu clearfix"Tfr>t<"dt-panelfooter clearfix"ip>',
                "oTableTools": {
                    "sSwfPath": "scripts/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
                }
          });

PHP代码:

<?php
require_once dirname(__FILE__) . ("/../db_connection.php");
require_once dirname(__FILE__) . ("/../functions/common-functions.php");
    global $connection;
    $account_id = $_REQUEST['acct_id'];

  $aColumns = array( 'opportunity_id', 'opportunity_name','opportunity_stage_id', 'opportunity_close_date', 'opportunity_acccount_id', 

     'opportunity_amount', 'opportunity_type', 'opportunity_owner_id', 'opportunity_contact_id', 'opportunity_details');


  $sIndexColumn = "opportunity_acccount_id";

  $sTable = "opportunities_base";

  $sWhere = "opportunity_acccount_id = $account_id";  

  function fatal_error ( $sErrorMessage = '' )

  {

    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );

    die( $sErrorMessage );

  }

  $sLimit = "";

  if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )

  {

    $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".

      intval( $_GET['iDisplayLength'] );

  }





  $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" )

      {

        $sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".

          ($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";

      }

    }



    $sOrder = substr_replace( $sOrder, "", -2 );

    if ( $sOrder == "ORDER BY" )

    {

      $sOrder = "";

    }

  }
  /* 

   * Filtering

   */

  $sWhere = "";

  if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )

  {

    $sWhere = "WHERE (";

    for ( $i=0 ; $i<count($aColumns) ; $i++ )

    {

      $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysqli_real_escape_string($connection,  $_GET['sSearch'] )."%' OR ";

    }

    $sWhere = substr_replace( $sWhere, "", -3 );

    $sWhere .= ')';

  }       
  /* Individual column filtering */

  for ( $i=0 ; $i<count($aColumns) ; $i++ )

  {

    if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )

    {

      if ( $sWhere == "" )

      {

        $sWhere = "WHERE ";

      }

      else

      {

        $sWhere .= " AND ";

      }

      $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysqli_real_escape_string($connection, $_GET['sSearch_'.$i])."%' ";

    }

  }


  /*

   * SQL queries

   * Get data to display

   */

  $sQuery = "

    SELECT SQL_CALC_FOUND_ROWS <code>".str_replace(" , ", " ", implode("`, `", $aColumns))."</code>     FROM   $sTable

    $sWhere

    $sOrder

    $sLimit

    ";

  $rResult = mysqli_query( $connection, $sQuery ) 

      or die("Error: ".mysqli_error($connection));



  /* Data set length after filtering */

  $sQuery = "

    SELECT FOUND_ROWS()

  ";

  $rResultFilterTotal = mysqli_query( $connection, $sQuery ) or die("Error: ".mysqli_error($connection));

  $aResultFilterTotal = mysqli_fetch_array($rResultFilterTotal);

  $iFilteredTotal = $aResultFilterTotal[0];



  /* Total data set length */

  $sQuery = "

    SELECT COUNT(`".$sIndexColumn."`)

    FROM   $sTable

    $sWhere

  ";

  $rResultTotal = mysqli_query($connection, $sQuery ) or die("Error: ".mysqli_error($connection));

  $aResultTotal = mysqli_fetch_array($rResultTotal);

  $iTotal = $aResultTotal[0];

  /*

   * Output

   */

  $output = array(

    "sEcho" => intval($_GET['sEcho']),

    "iTotalRecords" => $iTotal,

    "iTotalDisplayRecords" => $iFilteredTotal,

    "aaData" => array()

  );


  while ( $aRow = mysqli_fetch_array( $rResult ) )

  {

    $row = array();   

     //$row[] =  $OpenAccountTasks;

    $row[] = '<img src="../assets/advanced-datatable/examples/examples_support/details_open.png">';

    for ( $i=0 ; $i<count($aColumns) ; $i++ )

    {

      if ( $aColumns[$i] == "opportunity_name" )

      {

        /* Special output formatting for 'version' column */

       //$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];

        $row[] = '<a href="AccountProfile.php?acctname=' .$aRow[ $aColumns[$i] ].'">' . $aRow[$aColumns[$i]] . '</a>';

      }

      if ( $aColumns[$i] == "opportunity_stage_id" )

      {

        $opportunity_stage_name = get_opportunity_stages($aRow['opportunity_stage_id']);

          $row[] = $opportunity_stage_name;

      }

      if ( $aColumns[$i] == "opportunity_owner_id" )

      {

        $opportunity_owner = get_user_info($aRow['opportunity_owner_id']);

        while ($owner_id = mysqli_fetch_array($opportunity_owner)) {

           $row[] = $owner_id['user_full_name'];

        }

      }

      if ( $aColumns[$i] == "opportunity_contact_id" )

      {

        $opportunity_contact = get_contact_info($aRow['opportunity_contact_id']);

        while ($contact= mysqli_fetch_array($opportunity_contact)) {

           $row[] = $contact['contact_fname'].' '. $contact['contact_lname'];

        }



      }

      else if ( $aColumns[$i] != ' ' )

      {

        /* General output */

        $row[] = $aRow[ $aColumns[$i] ];

      }

    }

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

  }


  echo json_encode( $output );

?>

任何指针都表示赞赏。

2 个答案:

答案 0 :(得分:0)

试试这个,如果它不起作用,您可以使用var_dump($sWhere)var_dump($sQuery)

发表评论吗?
<?php
    require_once dirname(__FILE__) . ("/../db_connection.php");
    require_once dirname(__FILE__) . ("/../functions/common-functions.php");

    global $connection;
    $account_id = $_REQUEST['acct_id'];

    $aColumns = array(
        'opportunity_id', 'opportunity_name', 'opportunity_stage_id',
        'opportunity_close_date', 'opportunity_acccount_id', 'opportunity_amount',
        'opportunity_type', 'opportunity_owner_id', 'opportunity_contact_id',
        'opportunity_details'
    );

    $sIndexColumn = "opportunity_acccount_id";
    $sTable       = "opportunities_base";

    function fatal_error($sErrorMessage = '')
    {
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
        die($sErrorMessage);
    }

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

    $sOrder = "";
    if (isset($_GET['iSortCol_0'])) {
        $orderBy = array();
        for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
            if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                $orderBy[] = "`" . $aColumns[intval($_GET['iSortCol_' . $i])] . "` "
                    . ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc');
            }
        }

        $sOrder = "ORDER BY  " . implode(', ', $orderBy);
    }


    /**
     * Filtering
     */
    $sWhere = "";

    if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
        $where = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            $where[] = "`" . $aColumns[$i] . "` LIKE '%" . mysqli_real_escape_string($connection, $_GET['sSearch']) . "%'";
        }

        $sWhere = "WHERE (" . implode(' OR ', $where) . ')';
    }


    /* Individual column filtering */
    $where = array("opportunity_acccount_id = $account_id");
    for ($i = 0; $i < count($aColumns); $i++) {
        if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
            $where[] = "`" . $aColumns[$i] . "` LIKE '%" . mysqli_real_escape_string($connection, $_GET['sSearch_' . $i]) . "%'";
        }
    }
    if (count($where)) {
        $sWhere = ($sWhere === '' ? 'WHERE ' : $sWhere . ' AND ') . implode(' AND ', $where);
    }

    /**
     * SQL queries
     * Get data to display
     */
    $sQuery = "SELECT SQL_CALC_FOUND_ROWS <code>" . str_replace(" , ", " ", implode("`, `", $aColumns)) . "</code>     FROM   $sTable
          $sWhere
          $sOrder
          $sLimit
          ";

    $rResult = mysqli_query($connection, $sQuery) or die("Error: " . mysqli_error($connection));


    /* Data set length after filtering */
    $sQuery = "SELECT FOUND_ROWS()";

    $rResultFilterTotal = mysqli_query($connection, $sQuery) or die("Error: " . mysqli_error($connection));
    $aResultFilterTotal = mysqli_fetch_array($rResultFilterTotal);
    $iFilteredTotal     = $aResultFilterTotal[0];


    /* Total data set length */
    $sQuery = "SELECT COUNT(`" . $sIndexColumn . "`)
          FROM   $sTable
          $sWhere
        ";

    $rResultTotal = mysqli_query($connection, $sQuery) or die("Error: " . mysqli_error($connection));
    $aResultTotal = mysqli_fetch_array($rResultTotal);
    $iTotal       = $aResultTotal[0];

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


    while ($aRow = mysqli_fetch_array($rResult)) {

        $row = array();
        //$row[] =  $OpenAccountTasks;
        $row[] = '<img src="../assets/advanced-datatable/examples/examples_support/details_open.png">';

        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "opportunity_name") {
                /* Special output formatting for 'version' column */
                //$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
                $row[] = '<a href="AccountProfile.php?acctname=' . $aRow[$aColumns[$i]] . '">' . $aRow[$aColumns[$i]] . '</a>';
            }

            if ($aColumns[$i] == "opportunity_stage_id") {
                $opportunity_stage_name = get_opportunity_stages($aRow['opportunity_stage_id']);
                $row[]                  = $opportunity_stage_name;
            }

            if ($aColumns[$i] == "opportunity_owner_id") {
                $opportunity_owner = get_user_info($aRow['opportunity_owner_id']);

                while ($owner_id = mysqli_fetch_array($opportunity_owner)) {
                    $row[] = $owner_id['user_full_name'];
                }
            }

            if ($aColumns[$i] == "opportunity_contact_id") {
                $opportunity_contact = get_contact_info($aRow['opportunity_contact_id']);
                while ($contact = mysqli_fetch_array($opportunity_contact)) {
                    $row[] = $contact['contact_fname'] . ' ' . $contact['contact_lname'];
                }

            } else if ($aColumns[$i] != ' ') {
                /* General output */
                $row[] = $aRow[$aColumns[$i]];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode($output);
?>

答案 1 :(得分:0)

我能够弄清楚。 目标是在Ajax请求中传递一个初始化DataTable的变量,这样我只能显示与传递的帐户ID相关的结果。 这是Ajax请求:

  var acct_id = $('#acct_id').val();
  var oTable = $('#opportunities_table').dataTable( {
      // "aoColumnDefs": [
      //     { "bSortable": false, "aTargets": [ 0 ] }
      // ],
    "aaSorting": [[0, 'asc']],
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "../includes/functions/opportunity_json.php",
    "fnServerParams": function ( aoData ) {
                    aoData.push( {"name": "account_id", "value": acct_id} );
                  },
            "aoColumns": [
    { "mData": "0" },
    { "mData": "2" },
    //Begin actual rows
    { "mData": "6" },
    { "mData": "10" },
    { "mData": "12" },
    { "mData": "8" },
    { "mData": "4" },

  ],
  "sDom": '<"dt-panelmenu clearfix"Tfr>t<"dt-panelfooter clearfix"ip>',
        "oTableTools": {
            "sSwfPath": "scripts/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
        }

  });

这是PHP代码:

   $account_id = $_REQUEST['account_id'];
  if ( isset($account_id)  && $account_id != "" ) {

    if ($sWhere) $sWhere .= " AND opportunity_acccount_id=".mysqli_real_escape_string( $connection, $account_id );

    else $sWhere = " WHERE opportunity_acccount_id=".mysqli_real_escape_string($connection, $account_id );
  }

希望这会有所帮助。

谢谢。