Send data from a table in a modal to a php table using php and jquery

0

I have a bootstrap modal to which I load data from my database in mysql what I want it to do, is that by clicking on the add button I add the product of the modal row to a table in php in another page and when I gave it to another product, I added the following and so on. What it does now is load the first data that it sent to it and later when loading the second it deletes the one that previously sent, then what I want is that it makes a list. I appreciate any help.

This is the modal.

What I need is that you send me the data of the row here, in this table. But when sending the first data the next one deletes the first as if it will be updated. What I need is that you list them.

I enclose the code of the file agreg.php

<?php
require_once("../clases/conexion.php");
$id = $_POST['codigo'];
$c = $_POST['canti'];
$sql = "select * from tbl_producto where codigo = '$id'";
$result = mysqli_query($con, $sql);
?>
<table class="table">
  <tr>
  <th class='text-center'>CODIGO</th>
  <th class='text-center'>CANT.</th>
  <th>DESCRIPCION</th>
  <th class='text-right'>PRECIO UNIT.</th>
  <th class='text-right'>PRECIO TOTAL</th>  
  </tr>
  <?php    
     while ($row = mysqli_fetch_array($result)) {
     $codigo=$row['codigo'];
     $producto=$row['nombre'];
     $marca=$row['marca'];
     $precio=$row['precio'];
     $preciofinal = $precio*$c;
  ?>
  <tr>
   <td class="text-center"><?php echo $codigo; ?></td>
   <td class="text-center"><?php echo $c; ?></td>
   <td><?php echo $producto.' '.$marca; ?></td>
   <td class="text-right"><?php echo $precio; ?></td>
   <td class="text-right"><?php echo $preciofinal; ?></td>
   <td class='text-center'><a href="#" onclick=""><i class="glyphicon glyphicon-trash"></i></a></td>    
   </tr>
  <?php
    }
  ?>
 <tr>
  <td class='text-right' colspan=4>SUBTOTAL $</td>
  <td class='text-right'></td>
  <td></td>
 </tr>
 <tr>
   <td class='text-right' colspan=4>IGV $</td>
   <td class='text-right'></td>
  <td></td> 
 </tr>
<tr>
 <td class='text-right' colspan=4>TOTAL $</td>
 <td class='text-right'></td>
 <td></td>
</tr>
</table>

This is the function with which I sent you the data for the query

function agregar(id){  
 var cant = document.getElementById('cantidad_'+id).value;
      $.ajax({
      type: 'POST',
      url: "servlet/agregaraPHP.php",
      data: "codigo="+id+"&canti="+cant,
      success: function (r){
      $("#resultados1").html(r);
      }                                
      });
      }

And this is the code of the bootstrap modal

     <!-- Modal Busca Producto-->
    <div class="modal fade" id="AgregarPro" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="myModalLabel">Buscar productos</h4>
    </div>
    <div class="modal-body">
    <form class="form-horizontal">
    <div class="form-group">                                              
    <div class="col-sm-6">
    <input type="text" class="form-control" id="filtrar" placeholder="Buscar productos">
    </div>
    <a href="#" id="bus"><i class='glyphicon glyphicon-search'></i> Buscar</a>
                  </div>
                </form>                 
                                  <div class="outer_div">                                          
                                      <?php
                                        require './clases/conexion.php';
                                        $sql = "select * from tbl_producto";
                                        $result = mysqli_query($con, $sql);
                                      ?>       
                                        <div class="table-responsive">
                                        <table class="table">
                                            <tbody class="buscar">    
                                        <tr  class="warning">
                                            <th>Código</th>
                                            <th>Producto</th>
                                            <th>Marca</th>  
                                            <th><span class="pull-right">Cant.</span></th>
                                            <th><span class="pull-right">Precio</span></th>
                                            <th class='text-center' style="width: 36px;">Agregar</th>
                                        </tr>
                                        <?php
                                            while ($row = mysqli_fetch_array($result)) {
                                            $codigo=$row['codigo'];
                                            $producto=$row['nombre'];
                                            $marca=$row['marca'];
                                            $cantidad=$row['cantidad'];
                                            $precio=$row['precio'];                                            
                                        ?>
                                        <tr>
                                            <td><?php echo $codigo; ?></td>
                                            <td><?php echo $producto; ?></td>
                                            <td><?php echo $marca; ?></td>
                                            <td class='col-xs-1'>
                                                <div class="pull-right">
                                                    <input type="text" class="form-control" style="text-align:right" id="cantidad_<?php echo $codigo; ?>" value="<?php echo $cantidad; ?>">
                                                </div>
                                            </td>
                                            <td class='col-xs-2'>
                                                <div class="pull-right">
                                                    <input type="text" class="form-control" style="text-align:right" id="precio" value="<?php echo $precio; ?>">
                                                </div>
                                            </td>
                                            <td class='text-center'>
                                                <a class='btn btn-info'href="#" onclick="agregar(<?php echo $codigo; ?>)"><i class="glyphicon glyphicon-plus"></i></a>
                                            </td>
                                        </tr>
                                        <?php    
                                        }               
                                        ?>
                                            </tbody>
                                        </table>
                                        </div>
                                  </div><!-- Datos ajax Final -->
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>                  
              </div>
            </div>
          </div>
        </div>

Please, I thank you for your help.

    
asked by Mario Davila 16.01.2017 в 02:09
source

2 answers

1

Good, first of all comment that nowadays it is not very "attractive" to do it this way, PHP can not show the content more than when the page is rendered when reloading, so minimum will have to do a recharge for each product you add .

After reading the code I see that your ajax function sends a unique id (and not the collection of the current + the new one), so the previous ones are lost and will not show more than one result, in the for it will only enter once.

There are several ways to solve it My recommendation is the following: First I would create a small PHP script that gives you the info of each product

require_once("../clases/conexion.php");

function getProducto($id) {
    $id = $_POST['codigo'];
    $c = $_POST['canti'];
    $sql = "select * from tbl_producto where codigo = '$id'";
    $result = mysqli_query($con, $sql);
    $row = mysqli_fetch_array($result)

    // Generamos un array de respuesta
    $codigo=$row['codigo'];
    $producto=$row['nombre'];
    $marca=$row['marca'];
    $cantidad=$row['cantidad'];
    $precio=$row['precio'];

    $arrayProducto = array (
        'codigo' => $row['codigo'],
        'nombre' => $row['nombre'],
        ...
    );

    return json_encode($arrayProducto);
}

With this and your ajax function (changing the url line to the address of the previous script, eg: url: "loquesea/getproducto.php" ) you can collect the info of each product and add them to the table.

Example:

$('#tu-tabla tbody').append('<tr><td>' + result.codigo + '</td><td> ' + result.nombre ...

So you can add products dynamically, I've put an id (# your-table) to differentiate it from the other or others that you can have + the label inside each table to be able to handle the content without affecting the header nor to the summary.

Another option is to copy the info directly from the first table if you have all the information you need to have in the second one (as I think it is in this case).

First you get the info of the line in which you clicked the add button: You add to that <a> a class to be able to invoke the event from code and not inline, thus obtaining the event:

$('.agregar-producto').click(function (e) {
    var line = $(e.currentTarget).parent().parent().parent(); // Hasta llegar al <tr> raíz de la línea vamos..
    var result = {
        codigo: line.find('td')[0].text(),
        ...
        cantidad: line.find('input[name="cantidad"]').val()
        ...
    }
}

After that we save the result object in an array that will represent the contents of the tablaResumen.push('claveProducto', result); table, giving it the key of the id of each product. Doing so has the advantage that each time you add more than once the same product you can check if it already exists in the list and if it is, simply add the amount to the existing one instead of adding a new line for the same product.

There are many more details to add to this little app, such as the recommendation of a refrescarTabla() function that uses the list of saved objects to paint exactly what it contains after adding / removing a product, but that is no longer the context of the question.

I hope you have been helpful.

    
answered by 13.09.2017 в 11:13
0

Save it in a variable on the client's side, and when you're ready, send it. You can save the data of the table in a sessionStorage or localStorage. This is a temporary file that is created on the user's PC and has a max size of 5mb. the difference between sessionStorage and localStorage is that once you close the sessionStorage browser you lose all data, and localStorage does not.

To be able to invoke and call this function to save data, just place the following:

sessionStorage.setItem("tabla", datoTabla);
localStorage.setItem("tabla", datoTabla);

In this case you will save the data and list the table in "tableData" and then create the session or local variable, in the variable "table". If you want to save every time you enter, then call the session or the local, and add the code you need, if you draw the table, it means:

sessionStorage.setItem("tabla",sessionStorage.getItem("tabla") + datoTabla);
localStorage.setItem("tabla",localStorage.getItem("tabla") + datoTabla);

to rescue the values you can do it with:

sessionStorage.getItem("tabla");    
localStorage.getItem("tabla");    

and to eliminate just enough with

sessionStorage.removeItem("tabla");
localStorage.removeItem("tabla");

I hope it helps you, success: D

    
answered by 30.03.2017 в 20:48