Send data from an html table to php

Asked

Viewed 1,880 times

0

Hello

I have a table

<table>
  <thead>
    <th>Codigo</th>
    <th>Nome</th>
  </thead>
  <tr>`insira o código aqui`
     <td>1</td>
     <td>Carlos</td>
  </tr>
  <tr>
     <td>2</td>
     <td>Charles</td>
  </tr>
  <tr>
     <td>3</td>
     <td>José</td>
  </tr>
</table>

I wonder if there is how to "take" this data and send to php can be via json or even javascript

I tried to use that:

var dadosDataTabela = [];

function verificarTabela() {
    $('.item').each(function () {
       var todos_itens = {
           codigo   : $(this).children()[0].innerText,
           nome     : $(this).children()[1].innerHTML,

       };
       dadosDataTabela.push(todos_itens);
    });
}

and to send JSON.stringify(dadosDataTabela),

But I have not yet succeeded as you receive in php. To then send this data to the database

  • If you are using jQuery, there is a library for this: http://jsfiddle.net/cCzqn/80/

3 answers

1


There is a jQuery library that does the hard work (table-to-json), and from what I can see from the documentation, it’s quite customizable:

$('#converter-tabela').click( function() {
  var table = $('#tabela').tableToJSON();
  console.log(table);
  alert(JSON.stringify(table));  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/jquery.tabletojson.min.js" integrity="sha256-H8xrCe0tZFi/C2CgxkmiGksqVaxhW0PFcUKZJZo1yNU=" crossorigin="anonymous"></script>

<table id="tabela">
  <thead>
    <th>Codigo</th>
    <th>Nome</th>
  </thead>
  <tr>
     <td>1</td>
     <td>Carlos</td>
  </tr>
  <tr>
     <td>2</td>
     <td>Charles</td>
  </tr>
  <tr>
     <td>3</td>
     <td>José</td>
  </tr>
</table>
<button id="converter-tabela" >Converter</button>

  • cool! Sorry for my inexperience, and to receive in php would be json_decode(stripslashes($_POST['table']) ? If this is how to display in php?

  • It depends on how you want to receive this data in php, see that it creates an array with each row being an object, to test I recommend making one var_dump($_POST/$_GET/$_REQUEST)

  • i want to save this data in the database

1

With php you can do this: put the html code of the table in the $tab variable

$tab = "
<table>
<thead>
<th>Codigo</th>
<th>Nome</th>
</thead>
<tr>`insira o código aqui`
<td>1</td>
<td>Carlos</td>
</tr>
<tr>
<td>2</td>
<td>Charles</td>
</tr>
<tr>
<td>3</td>
<td>José</td>
</tr>
</table>
";

$er = "/<td(.*?)?>(.*?)+<\/td>/i";
preg_match_all ($er, $tab, $matches);

$td00=$matches[0][0];
$td01=$matches[0][1];
$td02=$matches[0][2];
$td03=$matches[0][3];
$td04=$matches[0][4];
$td05=$matches[0][5];

...("Insert into tabela (coluna1,coluna2,coluna3,coluna4,coluna5,coluna6)
values ('".$td00."','".$td01."','".$td02."','".$td03."','".$td04."','".$td05."')");

The function preg_match_all() will return an integer number with the number of occurrences found by the regular expression.

The function accepts 5 parameters, 3 mandatory and 2 optional. learn more at preg_match_all

$resultado = preg_match_all($pattern, $subject, $matches);
  • $Pattern shall be the expression regular,
  • $Subject will be the text (subject) the expression will search for
  • $Matches will be an array of occurrences (snippets found).

Or you can also take the $tab variable data from a file

$file = fopen("filename.html","r");

while(! feof($file))
  {
  $result=$result. fgets($file);
  }
fclose($file);

$tab = ".$result.";

0

Using the lib @Bonifazio indicated:

php data.

<?php
    $data = json_decode($_POST['dados_tabela'], true);

    /*
       $data terá o seguinte valor:
       array(
          array(
              "Codigo": 1
              , "Nome": "Carlos"
          )
          ... os demais nomes
       )

       É só percorrer o array com um laço e gravar no banco
    */
    // Retorna a confirmação para o javascript
    echo json_encode(array('success' => true));
?>

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://www.developerdan.com/table-to-json/javascripts/jquery.tabletojson.min.js"></script>
<script>
    $('#converter-tabela').click( function() {
        var table = $('#tabela').tableToJSON();
        console.log(table);
        alert(JSON.stringify(table)); 
        // Você envia os dados para o PHP utilizando AJAX
        $.ajax({
            // Enviamos os dados da tabela para um script PHP
            url: 'dados.php'
            , data: { dados_tabela: table }
            , method: 'POST'
        }).then(function(result) {
           // No retorno, apenas confirmamos
           if (result.success) {
               alert('Enviado para o servidor com sucesso!');
           }
       });
     });
</script>

<table id="tabela">
  <thead>
    <th>Codigo</th>
    <th>Nome</th>
  </thead>
  <tr>
     <td>1</td>
     <td>Carlos</td>
  </tr>
  <tr>
     <td>2</td>
     <td>Charles</td>
  </tr>
  <tr>
     <td>3</td>
     <td>José</td>
  </tr>
</table>
<button id="converter-tabela" >Converter</button>

Browser other questions tagged

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