CaptainDriftwood
CaptainDriftwood

Reputation: 5688

How to load a certain format of json into datatables

I have a JSON object that I am returning from an Ajax request that is formatted like the following:

{data:
[{"Sales1": "100", "Sales2": "200", "Sales3": "400"},
 {"Sales1": "150", "Sales2": "250", "Sales3": "450"}]};

How would I go about generating a datatables object with the columns names as "Sales1", "Sales2", etc., and the values in separate rows beneath each respective column? Also, lets say I wanted to have row labels to the left and right of the values, would that be possible?

Upvotes: 1

Views: 262

Answers (1)

Tim Harker
Tim Harker

Reputation: 2407

This is how you would go about generating a datatables object with the columns names as "Sales1", "Sales2", etc.

$(document).ready(function() {
  var source =
  
  {data:
  [{"Sales1": "100", "Sales2": "200", "Sales3": "400"},
   {"Sales1": "150", "Sales2": "250", "Sales3": "450"}]};
   
  $('#myDataTable').dataTable({
    "data": source.data,
    "aoColumns": [{
      "mData": 'Sales1',
    }, {
      "mData": 'Sales2'
    }, {
      "mData": 'Sales3'
    }]
  })
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.0/css/jquery.dataTables.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<table id="myDataTable">
  <thead>
    <tr>
      <th>Sales1</th>
      <th>Sales2</th>
      <th>Sales3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Upvotes: 3

Related Questions