PHP does not consider listing when it has a filter

Asked

Viewed 119 times

0

Top of the page:

<?php 
include "funcoes.php";
session_start();
$grupo_produto = $_SESSION['grupo_produto'];
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> 
        <script type="text/javascript" language="javascript" src="Scripts/jquery.dataTables.js"></script>
        <script type="text/javascript" charset="utf-8">
            $(document).ready(function() {
            $('#tabela_produtos').dataTable();
            } );
        </script>

I am making a system to perform orders and I am having a problem with datatable and PHP. I have a list of all the products.

I search for a product and put the desired amount as shown below:

inserir a descrição da imagem aqui

Until then, no big problems. I look for another product, put the quantity and finalize the order.

inserir a descrição da imagem aqui

The problem is that, at the end of the order, the only products it puts in the array are the last ones I chose (in this case, the 2 Guaraná Lata). He doesn’t consider those Kermit I chose in the beginning.

If I place the order without using the search field or if I search, put the quantity and delete what I searched (going back to the form with all products), it inserts normal.

I won’t put the Datatable code here because it’s too long.

Could you help me, please? Thanks in advance.

Code to choose product:

 <body>
    <form method="post" action="?acao=escolher_produto">
        <table id="tabela_produtos"  >
            <thead>
                <tr>   
                    <td>
                        Cod.
                    </td>
                    <td>
                        Nome
                    </td>
                    <td>
                        Preço
                    </td>
                    <?php 
                    if($grupo_produto == '0'){
                        ?>
                        <td>
                            Preço Broto
                        </td>
                        <td>
                            Preço Média
                        </td>
                        <td>
                            Preço Giga
                        </td>
                        <?php
                    }
                    ?>
                    <td>
                        Quantidade
                    </td>
                </tr>
            </thead>
            <?php 
            $array_produtos = mostrarProdutos($grupo_produto);
            ?>
            <tbody>
                <?php
                for($i=0; $i< count($array_produtos);$i++){
                    ?>
                    <tr>
                        <td>
                            <?php echo $array_produtos[$i][0]; ?>
                        </td>
                        <td>
                            <?php echo $array_produtos[$i][1]; ?>
                        </td>
                        <td>
                            <?php echo formataValor($array_produtos[$i][2]); ?>
                        </td>
                        <?php 
                        if($grupo_produto == '0'){
                            ?>
                            <td>
                                <?php echo formataValor($array_produtos[$i][3]);?>
                            </td>
                            <td>
                                <?php echo formataValor($array_produtos[$i][4]);?>
                            </td>
                            <td>
                                <?php echo formataValor($array_produtos[$i][5]);?>
                            </td>
                        <?php 
                        } 
                        ?>
                        <td> 
                            <input type="button" value="+" onclick="mais('<?php echo $i;?>')"/> <input type="number" id="<?php echo $i?>" name="<?php echo $i?>" /> 
                            <input type="button" value="-" onclick="menos('<?php echo $i;?>')"/>
                        </td>
                    </tr>
               <?php
                }
            ?>
            </tbody>
        </table>
        <input type="submit" value="Escolher">
    </form> 
</body>

Action by clicking choose:

if(@$_GET['acao'] == 'escolher_produto'){
$array_produtos = mostrarProdutos($_SESSION['grupo_produto']);
if(isset($_SESSION['array_pedido'])){
    $array_pedido = $_SESSION['array_pedido'];    
}else{
    $array_pedido = array();
}
$nenhum_produto = 0;
for($i=0; $i< count($array_produtos);$i++){
    if($_POST[$i] != 0){
        $codigo_produto = $array_produtos[$i][0];
        $descricao = $array_produtos[$i][1];
        $valor_unitario = $array_produtos[$i][2];
        $quantidade = $_POST[$i];
        while($quantidade > 0){
            array_push($array_pedido, array($codigo_produto,$descricao, $valor_unitario));
            $quantidade--;
        }
    }
    $nenhum_produto++;
}
if($nenhum_produto == 0){
    echo "<script> alert('Escolha algum produto'); history.back(); </script>";
}else{

    $_SESSION['array_pedido'] = $array_pedido;
    echo "<script> location.href ='grupo_produtos.php'; </script>";
}

}

  • The selected products are in $_SESSION['array_pedido']?

  • Just after I choose all products and click on "Choose" button, it stores in this $_SESSION['array_request'].

  • And where are the products chosen before the order is closed? Are you in any session?

  • They don’t stay anywhere. The products are only registered after clicking on the button (I choose all products and then click on the button choose)... For example: I type guarana, I choose 2... I type coca, I choose 2... Then when I click choose it should put all these 4 products in the array, but it does not.. he understands that the first product researched is not chosen. Now if I type guarana, I choose 2... Type coca, choose 2.. I delete what’s in the search field.. It goes back to the complete form and registers all products

  • Yes... but when you do the DB search it is done where? Where is this script? Is it in php or javascript? You could post the search script?

  • session_start() is where?

  • I edited the question and put the code snippet where it initializes Session and where it calls the javascript files. The search is done by the Datatable component.

  • Just a comment about the HTML there, with the input type="number" you wouldn’t need those increment and quantity decrease buttons, it already has those buttons there.

  • Thanks for the tip. I’ll fix it.

Show 4 more comments

1 answer

0

This datatable It works that way, just sends the form of what’s on the screen. To be able to send other fields, you need to do a little manual work rs.

What needs to be done is, when submitting the form, search for the form fields that are not being displayed on the screen and add them as hidden before sending, or within an equally invisible element.

The following code does that, searches the lines for anything input which is not visible in the datatable and adds to a div hidden. Also change the library inclusion part to use more up-to-date versions, and add in the middle to use the style of :

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jqu‌​ery.min.js"></script‌​>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jqc-1.12.4/dt-1.10.13/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/dt-1.10.13/datatables.min.js"></script>

JS

$(document).ready(function() {
  $('#tabela_produtos').dataTable();

  $('form').on('submit', function (e) {
    var seletor = 'input';
    var oForm = $(this);
    oForm.find('.dataTable').each(function () {
      var oTable = $(this).DataTable();
      var todos = $(oTable.rows().nodes()).find(seletor);
      var atual = $(oTable.rows({page:'current'}).nodes()).find(seletor);
      // adiciona os inputs que não estão visíveis ao form, escondendo eles
      var oDivOculto = $('<div>').attr('style', 'display: none');
      oDivOculto.append(todos.not(atual));
      oForm.append(oDivOculto);
    });
  });

} );
  • Thanks for the help, but I’m not very knowledgeable about Javascript and I don’t know in which part of the code this excerpt should be inserted. I tried to insert right at the beginning of the PHP action and at the beginning of the page along with the other Javascript calls, but it didn’t work. What is the right way to implement this code?

  • It may be right after the $('#tabela_produtos').dataTable();. There inside the $(document).ready. The $('form').on('submit', ... will always be executed when submitting the form.

  • I put it where you said and it still doesn’t pick up the selected products off the list..

  • I edited the code to include your javascript snippet, see if it looks like this. Something else, an error appears on the Chrome console when you submit the form? If you don’t know where it is, press F12, have a 'console' tab, clear any errors that appear first, do Ubmit and see if there were any errors. Another thing, are you up-to-date with dataTables? It could be that too.

  • I downloaded directly from the datatable website (datatables.net/download/index). As soon as the page is loaded, these errors appear: request.php:89 Uncaught Typeerror: $(...). on is not a Function(...)(Anonymous Function) @request.php:89(Anonymous Function) @ jquery.min.js:19each @jquery.min.js:12ready @ jquery.min.js:19(Anonymous Function) @jquery.min.js:19 And by submitting the form: Uncaught Typeerror $(...). on is not a request.php? acao=choose_product:89 Function(...)

  • I just noticed, your jquery is in a bit old version... change the line to include the script to <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  • By the way, jQuery is already in version 3.1. An upgrade can be interesting if you want to read jQuery update guide

  • When I update the line that calls Jquery, Datatable stops working... No longer displays the "search field"..

  • Did you get the version that doesn’t use jQuery by mistake? There are several buttons to press and it is a bit confusing. I updated the response with the HTML part of the inclusion scripts, swap and see if now goes...

  • Thanks for the help. I ended up solving the problem using jquery and ajax. By clicking the plus button it inserts the quantity into the array (and into the html, it consequently shows the updated value of the array) and by clicking the minus button it deletes 1 of the quantity.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.