Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert jquery datatable data as json

I am using jquery data table. I have a table like below,

<table id="employees">
  <thead>
     <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
   <tbody>
      <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
       <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
     </tbody>
</table>

I am converting the table into jquery datatable as $('#employees').DataTable()

I want to convert my jquery datatable as json format. Please help me to convert this as

[{"Id":"1", "Name":"Karthik","Email":"[email protected]","Phone":"1234"}]
like image 659
Karthikeyan Avatar asked Nov 28 '22 16:11

Karthikeyan


2 Answers

Try using DataTable rows function

 $('#YourDataTableID').DataTable().rows( { search: 'applied' } ).data().toArray();
like image 70
Andi AR Avatar answered Nov 30 '22 06:11

Andi AR


Try this

$(document).ready(function(){

   // Let's put this in the object like you want and convert to JSON (Note: jQuery will also do  this for you on the Ajax request)
   alert(JSON.stringify(tableToJSON($("#employees"))));
});


function tableToJSON(tblObj){  
   var data = [];
   var $headers = $(tblObj).find("th");
   var $rows = $(tblObj).find("tbody tr").each(function(index) {
   $cells = $(this).find("td");
   data[index] = {};
   $cells.each(function(cellIndex) {
     data[index][$($headers[cellIndex]).html()] = $(this).html();
   });    
});
  return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="employees">
  <thead>
     <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
   <tbody>
      <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
       <tr>
           <td>2</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>4567</td>
       </tr>
     </tbody>
</table>
like image 20
Parth Trivedi Avatar answered Nov 30 '22 04:11

Parth Trivedi