Ajax inside Datatables Custom Button Action

Ajax inside Datatables Custom Button Action

khrisdanielskhrisdaniels Posts: 1Questions: 1Answers: 0

I want to store datatables data inside an array or json format and use it to pass to php for FPDF use. In my datatable I created a custom button named "PDF", when the button is click I want to store the data and pass it into php via post. I have this code, but it wont work if I put ajax inside the action function of the custom button I made. It doesnt go to the url I declared. Here's the code:


$(document).ready(function() { var table = $('#stud_list').DataTable({ dom: 'Blfrtip', columnDefs: [{ targets: 1, className: 'noVis' }], buttons: [{ extend: 'excelHtml5', exportOptions: { columns: ':visible' } }, { extend: 'csvHtml5', exportOptions: { columns: ':visible' } }, { text: 'PDF', exportOptions: { columns: ':visible' }, action: function(e, dt, node, config) { $.ajax({ url: 'pdfViewStudent.php', type: 'post', data: table.row().data().toArray(), dataType: 'json', success: function(returnedData) { console.log(returnedData); } }); } }, 'colvis' ], columnDefs: [{ targets: -1, visible: false }], initComplete: function() { this.api().columns([4, 5, 6]).every(function() { var column = this; var select = $('') .appendTo($(column.footer()).empty()) .on('change', function() { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search(val ? '^' + val + '$' : '', true, false) .draw(); }); column.data().unique().sort().each(function(d, j) { select.append('' + d + '') }); }); } }); });

No error given in the console whenever I click the button but at the same time, nothing happens. It doesn't even direct me to the url given.

Answers

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947

    I placed your code into a test case and get this error when clicking the PDF button:

    Uncaught TypeError: table.row(...).data(...).toArray is not a function

    Maybe try replacing data: table.row().data().toArray(), with dt.data().toArray(). You can read about the dt parameter here: buttons.buttons.action.

    Kevin

  • allanallan Posts: 63,471Questions: 1Answers: 10,467 Site admin

    row().data() returns an array or an object (depending on your original data source). rows().data() returns a DataTables API instance and you can use toArray() to convert it to an array.

    Attempting to use row().data() and toArray() together will correctly throw an error.

    Allan

This discussion has been closed.