HTML Table data to JSON string in Javascript

Posts: 53

HTML Table data to JSON string in Javascript

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">

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

function getTableData(id) {
 // function to get table cells data (from: )
 // 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));
  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"]]

Adv. Posts: 01

Similar Topics