Pass HTML table data to servlet

3

Greetings, I have the following table in which I am adding items.

<table  class="table table-hover">
        <thead>
          <tr>
            <th>Codigo</th>
            <th>Descripcion</th>
            <th>Cantidad</th>
            <th>Valor unitario</th>
            <th>Valor total</th>
          </tr>
        </thead>
        <tbody id="tabProd" name="ProdLista">
          <tr>

          </tr>
        </tbody>
</table>

Javascript code with which I add rows

<script>
        function funcionFilas() {
            if (document.getElementById("prod").value!=="" &&
                    document.getElementById("cant").value!=="" &&
                    document.getElementById("precUni").value!=="") {
            var table = document.getElementById("tabProd");
            var row = table.insertRow(0);
            var celda1 = row.insertCell(0);
            var celda2 = row.insertCell(1);
            var celda3 = row.insertCell(2);
            var celda4 = row.insertCell(3);
            var celda5 = row.insertCell(4);
            celda1.innerHTML = document.getElementById("prod").value;
            celda2.innerHTML = document.getElementById("prod").value;
            celda3.innerHTML = document.getElementById("cant").value;
            celda4.innerHTML = document.getElementById("precUni").value;
            var valunit=document.getElementById("precUni").value*document.getElementById("cant").value;
            celda5.innerHTML = valunit;
            row.addEventListener("click", (function(){ alert('seleccionado'); }));
            }
            else{
                alert('Ingrese los campos de Cantidad, precio y producto');
            }
        }

My question is: How to pass all the data stored in this table to a servlet?

    
asked by Leo T 03.10.2016 в 00:28
source

2 answers

3

Suppose you enter a lot of data into the table, it is best to think about using JSON to send them to the servlet using AJAX . It's the friendliest way.

JavaScript

function tableToJSON() {
  let headers = document.querySelectorAll('th');
  let rows = document.querySelectorAll('tbody tr');
  let json = [];

  [].forEach.call(rows, (row, i) => {
    let cells = row.querySelectorAll('td');
    let data = {};
    cells.forEach.call(cells, (cell, x) => {
      let header = headers[x].textContent;
      let content = cell.textContent;
      data[header] = content;
    });
    json.push(data);
  });

  return json;
}

This simple function transforms a table format JSON . You can edit it to avoid x columns. Then you send that JSON by AJAX .

const form = document.getElementById('#form');


form.addEventListener('submit', handleFormSubmit);

function handleFormSubmit(e) {
  e.preventSubmit(); // evitamos el submit del fofrm
  let xhr = new XMLHttpRequest();
  xhr.open('POST', '/TuServlet');
  xhr.onload = function() {
    if(xhr.readyState === 4) {
      if(xhr.status === 200) {
        resetTable();
      } else {
        // ocurrió un error, manejarlo
      }
    }
  }
  xhr.send('data='+JSON.stringify(
    tableToJSON('tbl-people')
  ));
}

Java

In the servlet you get the JSON and with the help of the official library for Java we can map that JSON to Java objects.

String data = request.getParameter('data');
JSONArray array = new JSONArray(data);

// hacer algo con el json, por ejemplo leemos el primer objecto    
JSONObject fila1 = array.getJSONObject(0);
String producto = fila1.get('producto');
int cantidad = Integer.parseInt(fila1.get('cantidad'));

You can see the API here .

To make a classic submit, you can use hidden text boxes so that when sending the form, send these. For that you must create a hidden text box each time you add a new row.

celda5.innerHTML = valunit; // luego de ésta línea

var hidden0 = document.createElement('input');
hidden0.setAttribute('type', 'hidden');
hidden0.setAttribute('name', 'producto');
hidden0.value = document.getElementById("prod").value;
celda0.appendChild(hidden0);
// lo mismo para cada celda

And when sending the form, in the servlet you get the values. For example:

String[] productos = request.getParameterValues('producto');
    
answered by 04.10.2016 / 16:11
source
2

You can use a function that collects the values of each element of the table and send it to an url

    function enviar(){
        urlDestino = "http://destino.com";

        datosEnvio = "?prod=" + document.getElementById("prod").value + "&cant=" + document.getElementById("cant").value + "&precUni=" + document.getElementById("precUni").value;

        window.location.replace(urlDestino + datosEnvio);
    }
    
answered by 03.10.2016 в 12:18