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

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

Table of Contents
    Add a header to begin generating the table of contents
    Scroll to Top

    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’.

    was this article helpful?

    About the Author

    Partner + CEO

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

    21 Comments

    • how would I need to modify the table.html script to have each table cell an input field to dynamically enter data before sending. I tried a couple of things but didn’t get anywhere. THANK YOU for the extremely helpful post. I wish I had found it a couple of day ago!

      Reply
    • Hi Bob I have a html with 3 dropdown and 3 textboxes in a div row and I am using jquery repeater to repeat the row by clicking on add button. But when user add all the details in the respective div rows then how user should get all the textbox and dropdown values and then insert all those using jquery ajax call . How to iterate each div data and then insert data to server. Plz suggest me.

      Reply
    • Pingback: store html table values in a javascript array: GitHub File Free Download
    • Hey Bob,
      If I wanted to send the data back to my Controller rather than PHP, what would I need to do?

      Reply
      • Hi Avanish, I am assuming your controller is a javascript object with a callback function? If so, you should be able to change from the php call to an ajax call. Give me some more details and I’ll better answer your question.

        Reply
    • Very interesting and ideal for my requirements, but I’m not clear on the ajax portion.

      Does it go inside the ‘storeTblValues’ function or is it by itself? Could you post the entire code from beginning to end in one entry?

      Reply
    • Hi Bob ,

      I am using service now instance .
      And my problem is i have created a catalog item and it has a table like variable to insert the values in it.
      But once the item is ordered and when i check the table variable in the backend the values are completely empty .
      Shall i know how to resolve this issue?

      Code:

      Type
      Description
      Quantity

      Reply
      • Dinesh, I’m curious if you solved your issue? I’m not clear on your question. Are you using jQuery, or straight javascript? Either way, my first suggestion would be to store the table variable not in a local variable.

        Let me know more specifics and I can better help.
        …bob

        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
    • 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
    • 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
    • Thanks for the valuable and practical post
      How to send it to database(Mysql)?

      Reply

    Leave a Reply

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

    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

    Sign Up for Updates

    Get regular updates about what’s happening at FourFront!

    Enter your full name and email to be in the know about all things SEO, data solutions, and much more.

    Submit a Request