FourFront's Blog

Store HTML Table Values in a Javascript Array and Send to a PHP Script Using jQuery and Ajax

Updated: Mar 27, 2019

Code Files on GitHub

Sometimes you need to work from the client side back to the server. This tutorial demonstrates how to use jQuery to read the values in an HTML table and store the values in a Javascrip array that can be sent to a PHP script on a server. The code examples on this page are functional code snippets and can be viewed in the source for this page.

This tutorial is divided into the following steps for clarity:

  1. Use jQuery to read values in an HTML table
  2. Store HTML table values in a multidimensional Javascript array
  3. Convert Javascript array to JSON format
  4. Send JSON array to a PHP script using jQuery AJAX
  5. How to access a JSON encoded Javascript array in PHP

The following table will be used to demonstrate the code samples. The table has an id of “sampleTbl” (<table id=”sampleTbl”>) . This id will be used in the jQuery selector to access the table.

Task No. Date Description Task
1 December 24, 2012 Christmas Eve Make dinner
2 January 11, 2013 Anniversary Pickup flowers
3 March 7, 2013 Birthday Get present

Use jQuery to read the text values in an HTML table

The first step is setting up the code to access each table cell. The following jQuery code can be used to read each cell value in the above table. In this example, the value of each table cell is appended to the TableData variable. At the end of each row, a new line character (‘\n’) is appended to the string which makes the string more legible for output.

$('#sampleTbl tr').each(function(row, tr){
    TableData = TableData 
        + $(tr).find('td:eq(0)').text() + ' '  // Task No.
        + $(tr).find('td:eq(1)').text() + ' '  // Date
        + $(tr).find('td:eq(2)').text() + ' '  // Description
        + $(tr).find('td:eq(3)').text() + ' '  // Task
        + '\n';
});

The jQuery .each function is used to iterate through the table rows storing the table row identifier in the tr variable. This object represents the object of the active row. With each iteration the jQuery .find code is used to locate the column in the row using a zero based index value.

For example, the columns in the sample table will have index values of 0 – 3. The code: $(tr).find(‘td:eq(2)’).text() is used to read the text value in the Description column.

Store HTML Table Values into Multidimensional Javascript Array Object

Once you understand how to access the text values in each table cell, the next step is to save the values in an array. The following code will read the table and store the cell values in the TableData array.

var TableData = new Array();
    
$('#sampleTbl tr').each(function(row, tr){
    TableData[row]={
        "taskNo" : $(tr).find('td:eq(0)').text()
        , "date" :$(tr).find('td:eq(1)').text()
        , "description" : $(tr).find('td:eq(2)').text()
        , "task" : $(tr).find('td:eq(3)').text()
    }
}); 
TableData.shift();  // first row is the table header - so remove

For the sample table, the value of the row variable is the table row index and will range from 0 – 3. Since the header row is not needed, shift is used to pop it off the array: TableData.shift();

Convert a Javascript Array to JSON Format

Converting a Javascript array into JSON format is easy to do with jQuery-json which is a free jQuery plugin. Include this plugin on the page running your Javascript script.

<script src=”jquery.json-2.4.min.js”></script>

Once this plugin is installed, the $.toJSON function will serialize a javascript object into JSON format.

var TableData;
TableData = storeTblValues()
TableData = $.toJSON(TableData);

function storeTblValues()
{
    var TableData = new Array();

    $('#sampleTbl tr').each(function(row, tr){
        TableData[row]={
            "taskNo" : $(tr).find('td:eq(0)').text()
            , "date" :$(tr).find('td:eq(1)').text()
            , "description" : $(tr).find('td:eq(2)').text()
            , "task" : $(tr).find('td:eq(3)').text()
        }    
    }); 
    TableData.shift();  // first row will be empty - so remove
    return TableData;
}

The code to convert the TableData array to JSON format is: TableData = $.toJSON(TableData);

The TableData array is now ready to send to the server PHP script.
 

Send JSON Array to PHP

For this example, the jQuery $.ajax function is used. The variable type is set to “POST”, and the url is set to the sample PHP script.

var TableData;
TableData = $.toJSON(storeTblValues());
                
 $.ajax({
    type: "POST",
    url: "processJSONarray.php",
    data: "pTableData=" + TableData,
    success: function(msg){
        // return value stored in msg variable
    }
});

For this AJAX method, the JSON encoded TableData array is being passed to the server via the POST variable pTableData. The server response will be in the msg variable in the success handler

Process a JSON encoded Javascript array object in PHP

Once the JSON encoded array is sent to the destination URL, the PHP script will need to perform 2 steps before access the array values;

  1. Unescape the string values in the JSON array
  2. Decode the JSON array
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);

// Decode the JSON array
$tableData = json_decode($tableData,TRUE);

// now $tableData can be accessed like a PHP array
echo $tableData[1]['description'];

For this example, the PHP library function stripcslashes() is used. This is because during the JSON encoding process the quotes around the string variables were escaped. Without the stripslashes, the json_decode function will fail.

Once the array has been processed by the json_decode function, the array can be accessed as a normal PHP array: $tableData[1][‘description’]; will return the value ‘Anniversary’.

About The Author

Partner + CEO

With 35+ years of experience in technology and business, Bob is an expert programmer, software engineer, and digital marketer. Read More
Was this article helpful?

11 Comments

  • Thanks for the valuable and practical post
    How to send it to database(Mysql)?

    Reply
  • sir, i have a input tag in the table and by using this i m unable to fetch the data.
    whenever i echo the o/p it shows nothing(only blank space).

    Reply
    • Hello Karan, If you can, please reply with a sample of the html code that has this tag in it and I will be happy to respond.
      …bob

      Reply
  • Hello sir, let say I have a table named student and a field name matric_no and this field has up to three entries, I have selected all entries, now I want to assign each matric_no to different variables in JavaScript to be able to use it, how do I do that?

    Reply
    • Ak, You may want to try using a Map. The correct usage for storing data in the Map is through the set(key, value) method:

      let contacts = new Map()
      contacts.set(‘Jessie’, {phone: “213-555-1234”, address: “123 N 1st Ave”})

      You can also just move the values directly:
      var numbers = [65, 44, 12, 4];
      var newarray = numbers.map(myFunction)

      function myFunction(num) {
      return num * 10;
      }

      Reply
  • I have Form, with 2 tables, first small table has static names of the text input fields, i can call them directly. but the problem is the second table what i made, user can add more rows on button click, with that in mind that i had to add there few “empty” rows in place where the table should be split when it is printed out, because I could not make the page-break work on the rows of that table. So this “empty” rows needs to be ignored in the final gathering of data.
    All the rows from second table have unique name for each column, with number as row index. this number is in first column of this table, so It would be possible to compare it to this.
    Can you advice how to collect the data from Form like this? https://pastebin.com/aD5ufdYB

    Reply
    • Michal, can you test for an empty row as such?

      $('#sampleTbl tr').each(function (row, tr) {
      if ($(tr).find('td:eq(0)').text() != ''{ // change 0 to field # representing empty row
      TableData[row] = {
      "taskNo": $(tr).find('td:eq(0)').text()
      , "date": $(tr).find('td:eq(1)').text()
      , "description": $(tr).find('td:eq(2)').text()
      , "task": $(tr).find('td:eq(3)').text()
      }
      }
      });

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *