Ajax check new data with datatable

A great topic!

To check for new data with DataTables using AJAX, you can use the ajax.dataSrc option to specify a callback function that will be called whenever new data is received from the server. This callback function can then check if the new data contains any new records that need to be added to the table.

Here's an example of how you can achieve this:

$('#example').DataTable({
  "ajax": {
    "url": "your-ajax-url.php",
    "dataSrc": function (json) {
      // Check if the new data contains any new records
      var newRecords = [];
      $.each(json.data, function (index, row) {
        if (!table.rows().any(function (row) {
          return row.data()[0] === row.id;
        })) {
          newRecords.push(row);
        }
      });

      // Add the new records to the table
      table.rows.add(newRecords).draw();

      return json.data;
    }
  }
});

In this example, the dataSrc callback function is called whenever new data is received from the server. The function loops through the new data and checks if each record already exists in the table using the rows.any() method. If a record is not found in the table, it is added to the newRecords array.

Once all the new records have been identified, the rows.add() method is used to add them to the table, and the draw() method is called to redraw the table.

Note that you'll need to replace your-ajax-url.php with the URL of your AJAX endpoint, and table with the actual DataTables object.

Alternatively, you can use the ajax.complete option to specify a callback function that will be called whenever the AJAX request is complete. This function can then check if the new data contains any new records and add them to the table if necessary.

$('#example').DataTable({
  "ajax": {
    "url": "your-ajax-url.php",
    "complete": function (json) {
      // Check if the new data contains any new records
      var newRecords = [];
      $.each(json.data, function (index, row) {
        if (!table.rows().any(function (row) {
          return row.data()[0] === row.id;
        })) {
          newRecords.push(row);
        }
      });

      // Add the new records to the table
      table.rows.add(newRecords).draw();
    }
  }
});