0

In a Laravel project I am using DataTable JS (with server-side processing) to display tables. I want some custom functionalities for which I want to use DataTable's API, It has been a while trying things out but I can't clear the dataTable to insert new data and redraw it. Can you please help me with this.

Here is the relevant part of my JS code

Initialising Datatable

      dt = $('#dataTable').DataTable({
            'processing': true,
            'serverSide': true,
            'select': 'multiple',
            'ajax': {
                'url' :'{!! url('/') !!}/newOrderData',
                'type': 'POST',
                'headers': {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            },
            'columns': [
                { 'data': 'id', 'name': 'id' },
                { 'data': 'name', 'name': 'name' },
                { 'data': 'area', 'name': 'area' },
                { 'data': 'estimate', 'name': 'estimate' },
            ],
            "columnDefs": [
                { className: "orderId", "targets": [ 0 ] }
             ]
        });

Trying to clear data and redraw with new

        $('#areas').change(function(){
           var areaId = $(this).val();
           var token = "{{ csrf_token() }}";

           dt.clear().draw();

           $.post('{!! url('/') !!}/newOrderData',{area: areaId,_token:token}, function(newDataArray) {


                dt.rows.add(newDataArray); // Add new data
                dt.draw(); 

            });

        });

When the change event handler is fired, nothing happens, no errors, the table shows a processing sign but everything remains the same.

I was following this question. But the solution does not seem to work for me. Please help.

Prakhar Thakur
  • 1,209
  • 3
  • 13
  • 38

1 Answers1

0

Try this code to clear your data,

$('#areas').change(function(){
           var areaId = $(this).val();
           var token = "{{ csrf_token() }}";
           var dt = $('#dataTable').DataTable(); //create new object of the datatable
           dt.clear().draw();

           $.post('{!! url('/') !!}/newOrderData',{area: areaId,_token:token}, function(newDataArray) {


                dt.rows.add(newDataArray); // Add new data
                dt.draw(); 

            });

        });

I also faced this issue and this solution is worked for me.

Hope this will work for you.

Sunil Dora
  • 1,407
  • 1
  • 13
  • 26