Search code examples
javascriptjquerydatatablesdatatables-1.10

How to get current table id to add to ajax data when initialisation is used for multiple tables?


I have the following initialisation for multiple tables with the same class but different id attributes:

var $table = $('table.jobs');

$table.DataTable({

    ....
    ajax: {
        url: '/my-url',
        dataSrc: function (json) {

            return json.data
        },
        data: function(data) {

            data.table_id = $table.attr('id');
            // gives the same id for all tables

        }
    },
    ...
});

Is there a way I can identify which table is sending the ajax request? I'm trying to avoid duplicating the entire initialisation for every table.


Solution

  • You can try something like this:

    $('.table.jobs').each(function () {
        $('#'+$(this).attr('id')).dataTable({
             url: '/my-url',
        dataSrc: function (json) {
    
            return json.data
        },
        data: function(data) {
    
            data.table_id = $table.attr('id');
            // gives the same id for all tables
    
        }
    });