1

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?

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

3 Comments

No worries. You want row labels to the left and right of the values? Can you elaborate further? My mind spins as to what you're after.
Basically headers for the rows.
Tim, if I'm loading the data in via a function call when a button is pressed, how would that look?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.