I would like to fetch data on page load and then have filters that can be clicked to refetch the data. The query is a post request because the query parameters are complex and should be represented as json for logical grouping.
The code is as follows:
// table initialization
table = $('my_table').DataTable({
processing: true,
ajax: {
url: 'api/v1/get_documents',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: () => {
return JSON.stringify({
doc_filters: {
archived: false,
doc_type: 'accounting'
},
})
},
},
columns: my_columns,
});
$('#archive_button').click(() => {
table.ajax.data = () => {
return JSON.stringify({
project_filters: {
archived: true,
}
});
};
table.ajax.reload();
})
With the help of @andrewJames's suggestion I was able to refactor my code as follows:
// table initialization
table = $('my_table').DataTable({
processing: true,
ajax: {
url: 'api/v1/get_documents',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: () => {
archiveStatus = $('#archive_button').val();
documentType = $('#document_type').val();
return JSON.stringify({
doc_filters: {
archived: archiveStatus,
doc_type: documentType
},
})
},
},
columns: my_columns,
});
$('#archive_button, #document_type').click(() => {
table.ajax.reload();
})