Page 1 of 1

HTML Table data to JSON string in Javascript

Posted: 18 Nov 2014, 08:45
by Marius
Hi,
I have this HTML table. How can I get the TD data from each row in JavaScript (in JSON format) to be passed via Ajax to a PHP script?

Code: Select all

<table id="t_id">
<tbody>
  <tr>
    <th>col_1</th>
    <th>col_2</th>
    <th>col_3</th>
    <th>col_4</th>
  </tr>
  <tr>
    <td>156</td>
    <td>2668</td>
    <td>100.95</td>
    <td>1.82</td>
  </tr>
  <tr>
    <td>256</td>
    <td>618</td>
    <td>10.35</td>
    <td>1.82</td>
  </tr>
  <tr>
    <td>789</td>
    <td>28</td>
    <td>105.8</td>
    <td>15.89</td>
  </tr>
</tbody></table>

HTML Table data to JSON string in Javascript

Posted: 18 Nov 2014, 08:55
by Admin
Hi
Here is a JavaScript function that returns a 2-dimensional array with the <td> data of each row.
Then, use JSON.stringify(array) to convert the array into a string with JSON format.
Add the string into a POST or GET item that is passed with Ajax to PHP.
Then, in PHP use json_decode(); to convert the JSON string back into an array usable in PHP.

Code: Select all

<script>
function getTableData(id) {
 // function to get table cells data (from: https://coursesweb.net/ )
 // receives table ID. Returns 2 dimensional array with TD data in each row
  var t_rows = document.getElementById(id).querySelectorAll('tbody tr');    // rows from tbody
  var t_data = [];    // will store data from each TD of each row
  var ix = 0;    // index of rows in t_data

  // gets and dds td data in t_data
  for(var i=0; i<t_rows.length; i++) {
    var row_tds = t_rows[i].querySelectorAll('td');
    if(row_tds.length > 0) {
      t_data[ix] = [];
      for(var i2=0; i2<row_tds.length; i2++) t_data[ix].push((row_tds[i2].innerText || row_tds[i2].textContent));
      ix++;
    }
  }
  return t_data;
}

  /* USAGE */
var get_table_tds = getTableData('t_id');    // get the array with table data
var json_sr_tds = JSON.stringify(get_table_tds);    // JSON string with table data

// console.log(json_sr_tds);   // for debug
// result: [["156","2668","100.95","1.82"],["256","618","10.35","1.82"],["789","28","105.8","15.89"]]
</script>