简体   繁体   中英

Datatables -Reinitializing datatables in a function

I'm still learning how to code js and datatables and I'm working on a crud using ajax. I have this code here:

        load_data();

         function load_data(is_suppliers)
         {
          var dataTable = $('#product_data').DataTable({
           "processing":true,
           "serverSide":true,
           "order":[],
           "ajax":{
            url:"fetch.php",
            type:"POST",
            data:{is_suppliers:is_suppliers}
           },
           "columnDefs":[
            {
             "targets":[0,5,7,8],
             "orderable":false,
            },
           ],
          });
         }

This function is for column filtering and works with this code here:

         $(document).on('change', '#supplier_filter', function(){
          var supplier = $(this).val();
          $('#product_data').DataTable().destroy();
          if(supplier != '')
          {
           load_data(supplier);
          }
          else
          {
           load_data();
          }
         });

The problem is that the function initializes datatables:

          var dataTable = $('#product_data').DataTable({});

and i have already initialized datatables for my crud operations so i cant use this code. How can use this function so it can work with my crud operation?

If you define the table's ajax datasource via a function, then you can determine the parameters to send along with your AJAX request at the time the call is made. Then, you can reload the datasource whenever you want, and the most current value of the filter will be send along in the payload.

Replace

"ajax":{
  url:"fetch.php",
  type:"POST",
  data:{is_suppliers:is_suppliers}
},

With something like

ajax: function(data, callback, _settings) {
  $.ajax({
    type: 'POST',
    url: 'fetch.php',
    data: { is_suppliers: $('#supplier_filter').val() }
  }).then(function(res) {
    callback({ data: res });
  });
},

Now, when the table first loads, it'll fetch the filter value from the filter control, and then send it along as part of the AJAX request.

Later, you can load the data again with

$('#product_data').DataTable().ajax.reload();

And at that time, it will look again at the filter widget, get the value, and send the new value along with a new AJAX request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM