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

Bob’s endorphin level rises when he is coding. Read More »
Share This Article
Facebook
Twitter
Pinterest
LinkedIn
Related Content
About FourFront

FourFront uses data to provide digital marketing and market research services. In our blog, our team of analysts, strategists, and engineers provides tips, insights, analysis, and commentary.

Keep In Touch
Learn about new articles by following us on social:
Scroll to Top