Search code examples
jqueryhtmlhtml-tablecollect

Collect data from html table use jquery


I need collect data from the HTML table and send it to the server. I must use JQuery. there is my table

    <table id="table" border=1>
    <thead> <tr>
    <th>First</th>
    <th>Last</th>
    <th>Date of birth</th>
    <th>City</th>
    </tr></thead>
    <tbody>
    <tr>
    <td>TEXT1</td>
    <td>TEXT2</td>
    <td>TEXT3</td>
    <td>TEXT4</td>
    </tr>
    <tr>
    <td>TEXT5</td>
    <td>TEXT6</td>
    <td>TEXT7</td>
    <td>TEXT8</td>
     </tr>
    <tr>
    <td>TEXT9</td>
    <td>TEXT10</td>
    <td>TEXT11</td>
    <td>TEXT12</td>
   </tr>
   </tbody>
   </table>

Solution

  • You could achieve it in this manner,

    First we select all the data from the table cell's and then we send it to the server side via jquery ajax

    JQuery Code:

    <script  type="text/javascript" src="jquery-1.8.2.js"></script>
    <script type="text/javascript">
    $(function(){
        var dataArr = [];
        $("td").each(function(){
            dataArr.push($(this).html());
        });
        $('#sendServer').click(function(){
            $.ajax({
                  type : "POST",
                  url : 'server.php',
                  data : "content="+dataArr,
                  success: function(data) {
                      alert(data);// alert the data from the server
                  },
                  error : function() {
                  }
            });
        });
    });
    </script>
    

    Html code:

    <table id="table" border=1>
        <thead> <tr>
        <th>First</th>
        <th>Last</th>
        <th>Date of birth</th>
        <th>City</th>
        </tr></thead>
        <tbody>
        <tr>
        <td>TEXT1</td>
        <td>TEXT2</td>
        <td>TEXT3</td>
        <td>TEXT4</td>
        </tr>
        <tr>
        <td>TEXT5</td>
        <td>TEXT6</td>
        <td>TEXT7</td>
        <td>TEXT8</td>
         </tr>
        <tr>
        <td>TEXT9</td>
        <td>TEXT10</td>
        <td>TEXT11</td>
        <td>TEXT12</td>
       </tr>
       </tbody>
       </table>
    
    <input id="sendServer" name="sendServer" type="button" value="Send to Server" />
    

    in your server side PHP Code (here i am sending back what has been posted to server, just for the example)

    <?php 
    echo $_REQUEST['content'];
    ?>