Dynamically Populate jQuery DataTable with JSON data on AJAX request

Dynamically Populate jQuery DataTable with JSON data on AJAX request author(s): Chris Hennighan

by Wayne Humphrey

HTML

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
  <div class="panel">
    <button id="loadData" class="btn btn-default">Load Data</button>

    <table id="example" class="display" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Occupation</th>
          <th>Email Address</th>
        </tr>
      </thead>
    </table>
  </div>
</div>

CSS

#loadData {
  margin: 10px 0 15px 0;
}

JavaScript

$(function() {
  $("#example").DataTable();

  // Premade test data, you can also use your own
  var testDataUrl = "https://raw.githubusercontent.com/chennighan/RapidlyPrototypeJavaScript/master/lesson4/data.json"

  $("#loadData").click(function() {
    loadData();
  });

  function loadData() {
    $.ajax({
      type: 'GET',
      url: testDataUrl,
      contentType: "text/plain",
      dataType: 'json',
      success: function (data) {
        myJsonData = data;
        populateDataTable(myJsonData);
      },
      error: function (e) {
        console.log("There was an error with your request...");
        console.log("error: " + JSON.stringify(e));
      }
    });
  }

  // populate the data table with JSON data
  function populateDataTable(data) {
    console.log("populating data table...");
    // clear the table before populating it with more data
    $("#example").DataTable().clear();
    var length = Object.keys(data.customers).length;
    for(var i = 1; i < length+1; i++) {
      var customer = data.customers['customer'+i];

      // You could also use an ajax property on the data table initialization
      $('#example').dataTable().fnAddData( [
        customer.first_name,
        customer.last_name,
        customer.occupation,
        customer.email_address
      ]);
    }
  }
});