0

I have this file called crear_pedido_cliente.php, when nearly at the bottom there's a table with id="tabla". The user adds an article from a select, an ammount and the price, wich gives a total value per line; when the user clicks in the button "confirmar_linea", with jQuery those 4 fields are appended to the table. Here's the code:

<div id="contenido">
    <?php echo mensaje(); ?>
    <?php echo errores_de_formulario($errores); ?>
    <h2>Nuevo Pedido</h2>
    <form action="" name="form_pedido" method="post" novalidate>
        <p>Codigo del Pedido:
            <input type="text" class="encabezado_pedido" name="codigo_del_pedido" value="">
        </p>
        <p>Cliente:
            <span class="select">
            <select name="cliente_select" id="custom-select" class="encabezado_pedido">
            <?php
                $grupo_clientes = buscar_clientes();
                foreach($grupo_clientes as $item) {
                    echo "<option value=\"{$item["idCliente"]}\">{$item["razonSocial"]}</option>";
                }
            ?>  
            </select>
        </span>
        </p>
        <p>Fecha:
            <input type="text" class="encabezado_pedido" name="fecha_del_pedido" id="fecha" value="">
        </p>


        <button type="button" id="otro_pedido" name="otro_pedido" onclick="otro_pedido()">Otro Pedido</button>
        <button type="button" id="confirmar_encabezado" name="confirmar_encabezado" onclick="encabezado_listo()">Confirmar Datos</button> 

        <div id="detalles">
            <p>Articulo:

                <select id="articulo_select">
                <?php
                    $grupo_articulos = buscar_articulos();
                    foreach($grupo_articulos as $item) {
                        echo "<option value=\"{$item["idArticulo"]}\">{$item["descripcion"]}</option>";
                    }
                ?>  
                </select>
            </p>

                <p>Cantidad:
                <input type="text" class="detalle_pedido" name="cantidad" id="cantidad">
            </p>
            <p>Precio:
                <input type="text" class="detalle_pedido" id="precio" name="precio">
            </p>
        </div>
        <button type="button" id="confirmar_linea" name="" onclick="">Aceptar Linea</button>

        <input type="submit" id="guardar_pedido" name="submit" value="Guardar Pedido" onclick="">
        <br>
        <div id="detalles_actuales">
            <table id="tabla" border="1">
                <tr>
                    <td>
                        <label>Articulo</label>
                    </td>
                    <td>
                        <label>Cantidad</label>
                    </td>
                    <td>
                        <label>Precio Unitario</label>
                    </td>
                    <td>
                        <label>Precio de Linea</label>
                    </td>
                </tr>
            </table>
            <p>Total:
                <input type="text" id="total" name="precio_total" disabled value="0.00"/>
            </p>
        </div>
    </form>
    <br>
    <a href="lista_pedidos.php">Cancelar</a>
</div>
<script src="js/jquery.js" type="text/javascript"></script>
<script>

    $(document).ready(function () {
        var lista = 0;
    $('#confirmar_linea').click(function () {
        var articulo = $("#articulo_select").val();
        var cantidad = parseInt($("#cantidad").val(), 10);
        var precio = parseFloat($("#precio").val());
        var precio_t = cantidad * precio;
        $('#tabla').append("<tr>" + "<td>" + articulo + "</td>" + "<td>" + cantidad + "</td>" + "<td>" + precio + "</td>" + "<td>" + precio_t.toFixed(2) + "</td>" + "</tr>");
        var total = parseInt($("#total").val(), 10);
        $('input[name=precio_total]').val((total + precio_t).toFixed(2));
        var fila = [articulo, cantidad, precio, precio_t];
        lista = lista+1;
}); 
</script>

My problem is that at the begginning of the file I want to read with PHP all those rows inserted with jQuery to insert in a database. I've tried the following in the same file:

if (isset($_POST['submit'])) {

$url = "crear_pedido_cliente.php";

function get_data_from_table($url)
{
   // retrieve the content of that url
   $content = file_get_contents($url);

   // load into DOM
   $dom = new DOMDocument();
   $dom->loadHTML($content);

   // make xpath-able
   $xpath = new DOMXPath($dom);


   $query = "//tr/td";
   $elements = $xpath->query($query);


   $element = $elements->item(0);

   // get his parent element (tr)
   $tr = $element->parentNode;
   $data = array();

   // iterate over it's td elements
   foreach ($tr->getElementsByTagName("td") as $td) {
        // retrieve the content as text
        $data[] = $td->textContent;
   }

   // return the array of <td> contents
   return $data;
}

echo '<pre>';
print_r(get_data_from_table($url));
echo '</pre>';

}

The result, besides some warnings, are the first 4 elements in that table, the "titles" that are written in the table in HTML and wrapped with label tags.

Is there any issue with jQuery adding this that PHP doesn't recognize them as part of the DOM?

EDIT: I've tried this answer, using the Simple HTML Dom library. And the result is:

Array
{
}
Community
  • 1
  • 1
Juank
  • 155
  • 3
  • 13
  • 1
    I don't think I quite understand. When you enter the values, and then click `confirmar_linea` the only thing happening is the value(s) are added to the table on-screen. I think that might give the user some unexpected results. Once I click the button, the data isn't actually saved. I would insert the data right when the button is clicked. That would be easier to get the data as well since you'd only be dealing with one row at a time. [Check this thread](http://stackoverflow.com/questions/20769364/insert-data-through-ajax-into-mysql-database) for an ajax example – Damon Sep 09 '15 at 01:20
  • @Damon That's the intended use: when the user clicks on **confirmar_linea**, jQuery add the values in a row; then the user can continue to add more rows. When the user clicks on **submit**, then the real insert to the database must begin and thus PHP must iterate trough each tr inserted in the table. – Juank Sep 09 '15 at 01:38
  • You need to use AJAX (or a $_POST will do, but AJAX is more elegant). jQuery does not alter the physical php document, it only modifies it temporarily from the browser so those dynamically-added table rows are not really there on the server. – Rasclatt Sep 09 '15 at 02:01
  • @Rasclatt how can I do that without saving to the database? Remember that I have two buttons: the first one create each row of the table (confirmar_linea) and the second one (submit) insert all those rows in the database when the user finish loading all those data. – Juank Sep 09 '15 at 02:04
  • There are a couple ways, one is making the rows part of a form with hidden inputs, or you could get the contents (text/html) of the each `` that contains values you want to save, then pass those values in a data object in an ajax call. – Rasclatt Sep 09 '15 at 02:07
  • I forgot to clarify this *...you could get the contents (text/html) of the each ``...* would need to be done via javascript/jQuery. – Rasclatt Sep 09 '15 at 02:17

2 Answers2

1
<table id="table1" border="1">
   <tr>
      <th>EmployeeID</th>
      <th>Name</th>
      <th>Designation</th>
      <th>Process1</th>
      <th>Process2</th>
   </tr>
   <tr>
      <td>
         <input type="hidden" id="a1" class="firstName" value="1">
         0000011
      </td>
      <td>
         chidambaram
      </td>
      <td>
         Tech Lead
      </td>
      <td>
         <input type="hidden" id="a1" class="firstName" value="11">
         <input type="text" id="a1" class="firstName" value="text1">
      </td>
      <td>
         <input type="hidden" id="a1" class="firstName" value="22">
         <input type="text" id="a1" class="firstName" value="text2">
      </td>
   </tr>
   <tr>
      <td>
         <input type="hidden" id="a1" class="firstName" value="2">
         0000002
      </td>
      <td>
         Suresh
      </td>
      <td>
         Android Developer
      </td>
      <td>
         <input type="hidden" id="a1" class="firstName" value="33">
         <input type="text" id="a1" class="firstName" value="text3">
      </td>
      <td>
         <input type="hidden" id="a1" class="firstName" value="44">
         <input type="text" id="a1" class="firstName" value="text4">
      </td>
   </tr>
</table>

<button id="target">Click me</button>

Jquery

$("#target").click(function() {

    //storage        
    var data = {
        firstName: [],
        lastName: []
    }

    //loop through the td's
    $('table tr').each(function() {

        var tdlen = $(this).children('td').length
        var i = 0;

        $('td', this).each(function() {


            if (i == 0) {
                alert('Emp. ID is : ' + $(this).find("input[type='hidden']").val());
            }
            if (i > 2) {
                alert('ID is : ' +$(this).find("input[type='hidden']").val());
                alert('text value is : ' +$(this).find("input[type='text']").val());
            }
            i++;
        });

    });



});

https://jsfiddle.net/chidamca/ty30j2ju/ for demo

  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Rizier123 Mar 17 '16 at 12:41
0

Ok, so the answer here was to create a series of hidden inputs, something @Rasclatt was suggesting in a way. Then it's easy to iterate trough $_POST names with PHP.

Thanks everyone for your time

Juank
  • 155
  • 3
  • 13