DataTables example with Ajax

How to use DataTables with Ajax calls to fetch and fill the table with data. There are multiple ways to source the data for your table, Ajax being one of the more versatile methods.

Previous post for DataTables with PHP and MySQL.

View the CodePen example here.

DataTables example with Ajax

The DataTable script:

$(document).ready(function () {
  
  table = $("#animalsTable").DataTable({
    pageLength: 20,
    order: [],
    paging: true,
    searching: true,
    info: true,
    ajax: {
      url: "https://peachpuff.srv3r.com/api/index.php",
      method: "GET",
      data: {
        data_table: ""
      },
      dataSrc: ""
    },
    columns: [//Define colummns
      { data: "id" },
      { data: "guid" },
      { data: "name" },
      { data: "status" }
    ]
  });
  
});

On page load (ready) this will build the table by doing a GET request to the “API” which returns all the animal data for the table with 20 items each page as default.

Using dataSrc: "" means that the data is in a clean, non-nested array eg:

[
{"id":"1","guid":"ABC"},
{"id":"2","guid":"DEF"}
]

Rather than:

{
  "data": {
    "date": "2020-01-01 23:59:59",
    "value": "XYZ",
    "animals": [
      {
        "id": "1",
        "guid": "ABC"
      },
      {
        "id": "2",
        "guid": "DEF"
      }
    ]
  }
}

The HTML structure, including the table header row:

<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="card p-2">
        <h3 align="center">Animals</h3>
        <div class="table-responsive">
          <table id="animalsTable" class="table table-striped table-bordered">
            <thead>
              <tr>
                <td>Id</td>
                <td>GUID</td>
                <td>Name</td>
                <td>Status</td>
              </tr>
            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

You will need jQuery, DataTables plus Bootstrap for the styling:

<head>
    <title>datatables Ajax example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/dataTables.bootstrap4.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css"/>
</head>