Ajax inside Datatables Custom Button Action
Ajax inside Datatables Custom Button Action
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
I placed your code into a test case and get this error when clicking the PDF button:
Maybe try replacing
data: table.row().data().toArray(),
withdt.data().toArray()
. You can read about thedt
parameter here:buttons.buttons.action
.Kevin
row().data()
returns an array or an object (depending on your original data source).rows().data()
returns a DataTables API instance and you can usetoArray()
to convert it to an array.Attempting to use
row().data()
andtoArray()
together will correctly throw an error.Allan