簡體   English   中英

如何將從DataTable檢索的數據傳遞給PHP

[英]How to pass a data retrieved from DataTable to PHP

我已經能夠從DataTable的第一列檢索數據到jQuery上的警報。

但是現在,我需要將此數據傳遞給PHP,以便在查詢中使用以便從數據庫中檢索一些數據。

但是我不願意這樣做...有人可以幫助我嗎?

    <?php 

    include 'db.php';

    session_start();


      if(array_key_exists("matricula",$_COOKIE))
      {
          $_SESSION['matricula'] = $_COOKIE['matricula'];
      }

      if (array_key_exists("matricula",$_SESSION))
      {

      }
      else
      {
        echo "<script> window.location.replace('login.php') </script>";
      }
      ?>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Gestão Cartões Diária</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="font-awesome/css/font-awesome.css" rel="stylesheet">

    <link href="css/plugins/dataTables/datatables.min.css" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <link href="//cdn.datatables.net/plug-ins/1.10.15/sorting/currency.js" rel="stylesheet">

    <link href="https://cdn.datatables.net/select/1.2.2/css/select.dataTables.min.css"  rel="stylesheet" type="text/css"/>

</head>

<body>

    <div id="wrapper">


        <?php 
            $query = "SELECT `funcao` FROM `tb_usuarios` WHERE `matricula`='".mysqli_real_escape_string($conn,$_SESSION['matricula'])."'";
            $result = mysqli_query($conn,$query);
            $row = mysqli_fetch_array($result);
            if( $row['funcao'] == 'EMPREGADO')
            {
                include("layout_empregado.php");                
            }
            else
            {
                include("layout_supervisor.php");               
            }
        ?>

    </div>

        <?php
            if (isset($_POST['ano_gasto']) and isset($_POST['mes_gasto']))
            {
                $SQLSELECT = "SELECT * FROM tb_gastos_alimentacao WHERE matricula LIKE '".mysqli_real_escape_string($conn,$_SESSION['matricula'])."' AND ano LIKE'".$_POST['ano_gasto']."' AND mes LIKE '".$_POST['mes_gasto']."'"; 
            }
            else
            {
                $SQLSELECT = "SELECT * FROM tb_gastos_alimentacao WHERE matricula LIKE '".mysqli_real_escape_string($conn,$_SESSION['matricula'])."'";  
            }
        ?>

        <div class="row wrapper border-bottom white-bg page-heading">
            <div class="col-lg-10">
                <h2>Consulta Gastos Usuário <?php echo $_SESSION['matricula'] ?></h2>
                <ol class="breadcrumb">
                    <li>
                        <a href="#">Home</a>
                    </li>
                    <li class="active">
                        <strong>Gastos Cartão</strong>
                    </li>
                </ol>
            </div>
        </div>

        <div class="wrapper wrapper-content animated fadeInRight">

            <div class="row">
                <form method="post">
                    <div class="col-lg-12">
                        <div class="ibox float-e-margins">
                            <div class="ibox-title">
                                <h5>Dados do Usuário <?php echo ($_SESSION['matricula']) ?></h5>
                                <div class="ibox-tools">
                                    <a class="collapse-link">
                                        <i class="fa fa-chevron-up"></i>
                                    </a>
                                </div>
                            </div>
                            <div class="ibox-content">

                                <div class="row">
                                <div class="col-xs-2 form-group">
                                    <label>Matrícula</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['matricula']; ?>"/>
                                </div>
                                <div class="col-xs-7 form-group">
                                    <label>Portador do Cartão</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['nome']; ?>"/>
                                </div>
                                <div class="col-xs-3 form-group">
                                    <label>Nº Cartão</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['cartao']; ?>"/>
                                </div>
                                </div>

                                <div class="row">
                                <div class="col-xs-2 form-group">
                                    <label>Centro de Custos</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['centro_custo']; ?>"/>
                                </div>
                                <div class="col-xs-7 form-group">
                                    <label>Supervisão</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['supervisao']; ?>"/>
                                </div>
                                <div class="col-xs-3 form-group">
                                    <label>Lotação</label>
                                    <input class="form-control" type="text" disabled="disabled" value="<?php echo $dados_usuario['lotacao']; ?>"/>
                                </div>
                                </div>

                                <div class="row">
                                <div class="col-xs-2 form-group">
                                    <label>Mês</label>
                                    <select class="form-control m-b" id="cmbMesGasto" name="mes_gasto">
                                        <option value="%">TODOS</option>
                                        <option>Janeiro</option>
                                        <option>Fevereiro</option>
                                        <option>Março</option>
                                        <option>Abril</option>
                                        <option>Maio</option>
                                        <option>Junho</option>
                                        <option>Julho</option>
                                        <option>Agosto</option>
                                        <option>Setembro</option>
                                        <option>Outubro</option>
                                        <option>Novembro</option>
                                        <option>Dezembro</option>
                                    </select>
                                    <input type="hidden" name="mes_selecionado" id="mes_selecionado" value="" />
                                </div>
                                <div class="col-xs-2 form-group">
                                    <label>Ano</label>
                                    <select class="form-control m-b" id="cmbAnoGsto" name="ano_gasto">
                                        <option value="%">TODOS</option>
                                        <option>2015</option>
                                        <option>2016</option>
                                        <option>2017</option>
                                        <option>2018</option>
                                        <option>2019</option>
                                        <option>2020</option>
                                    </select>
                                    <input type="hidden" name="ano_selecionado" id="ano_selecionado" value="" />
                                </div>
                                <div class="col-xs-2 form-group">
                                    <button class="btn btn-primary" type="submit" name="pesquisa_data" id="pesquisa_data">Buscar</button>
                                    <button class="btn btn-primary" type="submit" name="teste" id="teste">Teste</button>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>Consulta aos Gastos do Usuário <?php echo ($_SESSION['matricula']) ?></h5>
                            <div class="ibox-tools">
                                <a class="collapse-link">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                            </div>
                        </div>
                        <div class="ibox-content">

                    <div class="table-responsive">
                        <table class="table table-striped table-bordered table-hover dataTables-example" id="tabela" >
                        <thead>
                            <tr>
                                <th>Data Lanc.</th>
                                <th>Núm. Trans.</th>
                                <th>Estabelecimento</th>
                                <th>Localidade</th>
                                <th>Valor</th>
                            </tr>
                        </thead>
                        <tbody>

                        <?php
                            $result_set =  mysqli_query($conn,$SQLSELECT);
                            while($row = mysqli_fetch_array($result_set))
                            {
                        ?>

                            <tr class="gradeX">
                                <td><?php echo $row['data_lancamento']; ?></td>
                                <td><?php echo $row['num_transacao']; ?></td>
                                <td><?php echo $row['estabelecimento']; ?></td>
                                <td><?php echo $row['localidade']; ?></td>
                                <td><?php echo $row['valor']; ?></td>
                            </tr>

                            <?php
                                }
                            ?>

                        </tbody>
                        <tfoot>
                        <tr>
                            <th>Data Lanc.</th>
                            <th>Núm. Trans.</th>
                            <th>Estabelecimento</th>
                            <th>Localidade</th>
                            <th>Valor</th>
                        </tr>
                        </tfoot>
                        </table>
                    </div>

                        </div>
                    </div>
                </div>
            </div>
            <button id="btn">Click</button>
        </div>



        <?php include("rodape.php"); ?>

    <!-- Mainly scripts -->
    <script src="js/jquery-2.1.1.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
    <script src="js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
    <script src="js/plugins/jeditable/jquery.jeditable.js"></script>
    <script src="js/plugins/dataTables/datatables.min.js"></script>
    <script src="//cdn.datatables.net/plug-ins/1.10.15/sorting/currency.js"></script>
    <script src="https://cdn.datatables.net/select/1.2.2/js/dataTables.select.min.js"></script>


    <!-- Custom and plugin javascript -->
    <script src="js/inspinia.js"></script>
    <script src="js/plugins/pace/pace.min.js"></script>

    <!-- Page-Level Scripts -->
    <script>
        $(document).ready(function(){
            $('.dataTables-example').DataTable({
                dom: '<"html5buttons"B>lTfgitp',
                columnDefs: [
                    {
                        targets: -1,
                        data: 'Valor',
                        render: $.fn.dataTable.render.number( '.', ',', 2, 'R$' )
                    }
                ],
                buttons: [
                    {extend: 'copy'},
                    {extend: 'csv'},
                    {extend: 'excel', title: 'ExampleFile'},
                    {extend: 'pdf', title: 'ExampleFile'},
                    {extend: 'print',
                     customize: function (win){
                        $(win.document.body).addClass('white-bg');
                        $(win.document.body).css('font-size', '10px');
                        $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
                        }
                    }
                ]

            });

        });

    //Código para selecionar uma linha da tabela
    $(document).ready(function() {
        var table = $('#tabela').DataTable();

        $('#tabela tbody').on( 'click', 'tr', function () {
            if ( $(this).hasClass('selected') ) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
            var matricula_recuperada = table.cell('.selected', 0).data();
            alert(matricula_recuperada);
        } );
    } );

    </script>

</body>

</html>

在最后20行,是我從DataTable檢索數據的地方,這就是我希望傳遞給php的數據。

這是桌子的照片...

完成禁忌

謝謝!

刪除警報並使用ajax例如:

var matricula_recuperada = table.cell('.selected', 0).data();

$.ajax({
  url: 'your url',
  method: 'post',
  data: {
    id: matricula_recuperada
  },
  success: function(response)
  {
    // Do what ever you want here
  }
});

考慮以下非常簡單的措施:

(1)用條目的主鍵ID豐富表行,以便稍后將此ID提交回服務器。 例如, <tr>上的data-id屬性:

<tr class="gradeX" data-entryID="<?= $row['data_id'] ?>">

(2)制定AJAX請求以提交此條目ID。

$('[data-entryID]').on('click', function() {
    $.ajax({
       url: 'handleClickedEntry.php',
       data: {
          entryID: $(this).attr('data-entryID')
       },
       success: function(data) {
          // The servers response as data
       }
    });
});

(3)創建一個PHP文件(或使用現有文件,只需確保具有唯一的URL)來處理您要對單擊的表行執行的操作。 也許像handleClickedEntry.php之類的東西,但請確保傳達操作的責任。

在此文件內,您將通過AJAX提交的數據作為$_REQUEST數組。 因此,您可以輕松訪問給定的條目ID: $_REQUEST['entryID']

如果要響應數據,請使用json_encode函數將PHP數組轉換回JSON並回顯它。 例如:

$newData = ['entryID' => 3, 'someProperty' => 'test'];
$jsonResponse = json_encode($newData);

echo $jsonResponse;

$jsonResponse將是AJAX調用內success函數中使用的data變量。 使用$.parseJSON將其轉換回來。

編輯:如果要使用相同的文件來處理單擊操作,請進行如下修改:

$('[data-entryID]').on('click', function() {
    $.ajax({
       url: 'yourFile.php',
       data: {
          entryID: $(this).attr('data-entryID'),
          action: 'handleRowClick'
       },
       success: function(data) {
          // The servers response as data
       }
    });
});

剩下的唯一事情是檢查HTTP請求是否源自此AJAX調用:

if($_REQUEST['action'] == 'handleRowClick') {
    // Handle the AJAX request here
}

我完全不建議這樣做,但是鑒於您的解決方案,它可能是最合適的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM