Home > Blockchain >  Pass DataTable reference to the callback function on load
Pass DataTable reference to the callback function on load

Time:03-03

My current code is:

var CommissionLogs = $("#CommissionLogs").DataTable({       
     ajax: {
         url: ajaxurl   '?action=pos&post_action=get_commissions'
      },
    'initComplete': function (settings, json){
        //possible to access 'this'
        this.api().columns(1);
    }
  });

I improved the code above as below with help :

var CommissionLogs = $("#CommissionLogs").DataTable({       
     ajax: {
         url: ajaxurl   '?action=pos&post_action=get_commissions'
      },
    'initComplete': function(settings, json){ 
        callbackFunction(settings);
     }
  });

 function callbackFunction(settings){
     var api = new $.fn.dataTable.Api( settings );
     // api is accessible here.
 }

Update :

Now I can access api from callback function. But I want use same callback with load() as below code.

CommissionLogs.ajax.url( newAjaxURL ).load( callbackFunction(), true);

But settings param is not accessible in load function.

I can clear and destroy datatable and re initialize always. But what will be the right way.

CodePudding user response:

I think you need settings:

https://datatables.net/reference/type/DataTables.Settings

$('#example').dataTable( {
    "initComplete": function(settings, json) {
        myFunction(settings);
    }
});

function myFunction(settings){
    var api = new $.fn.dataTable.Api( settings );
 
    // Output the data for the visible rows to the browser's console
    // You might do something more useful with it!
    console.log( api.rows( {page:'current'} ).data() );
}

Other option is re-use your var CommissionLogs variable throughout the code without using this, I recommend strongly this last option.

CodePudding user response:

The dataTable.ajax.url().load() has not access to settings.

So can not call a callback function with settings.

But possible to use callback function without settings.

So here is an alternative way to use settings.

 CommissionLogs.clear();// clear the table
 CommissionLogs.destroy();// destroy the table
 CommissionLogs = $("#CommissionLogs").DataTable({           
         ajax: {
            url: newAjaxUrl
         },
        'initComplete': function (settings, json){
            callbackDatatableFunciton(settings);
        }
    }); 
  • Related