How to initialize DataTables with columns through server processing?
How to initialize DataTables with columns through server processing?
Hello. When using server processing, we write the columns immediately through:
columns: [{'data': 'column1'}]
But the thing is, I don't know the number of columns in advance.
Is it possible to get columns and rows in ajax and display them?
Something like this:
$("#full_depth").DataTable({
processing: true
"server side": true
ajax: {
"url": './ajax/getDataFullDepth.php',
"type": "GET",
data: {
test: 'test'
},
},
"responsive": true
lengthChange: true
"autowidth": false
pageLength: 25
"order": [],
"language": dataTableLanguage,
}).buttons().container().appendTo('#dataTableManual_wrapper .col-md-6:eq(0)');
})
But I don't know how to transfer and initialize columns through ajax. Can I have an example please?
Answers
Datatables doesn't provide an option to define the columns after initialization. You will need to fetch the column info and build the columns object before Datatable initialization. Something like this example which builds a
columns
variable that is used to initialize thecolumns
option. It usescolumns.title
to define the column headers. Due to limitations of the JS BIN environment the jQuery ajax() fetches all the data. Your solution should have a way to only return the column definitions.Also see this FAQ.
Kevin
@kthorngren Do you mean I need to get away from server side processing and add my own ajax query that will get data about columns and rows?
That is, I need to write an Ajax query, get columns and rows. Delete existing columns. Add new ones. And based on them add lines?
My task is simply such that each Ajax request will have different columns. Do you understand?
No. Sorry I forgot to post a link to the example:
https://live.datatables.net/qimukefe/1/edit
The jQuery ajax() request is meant to get the column configuration. Then Datatables will use
ajax
to fetch the row data.With server side processing any sort, search or page change will send a request to the server for the updated page's data. Are you planning to change the columns for these events?
Do you need server side processing enabled?
To change the Datatables configuration you will need to use
destroy()
and reinitialize with the new configuration.Kevin