How to initialize DataTables with columns through server processing?

How to initialize DataTables with columns through server processing?

dwpointdwpoint Posts: 9Questions: 3Answers: 0

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

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951
    edited May 2023

    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 the columns option. It uses columns.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

  • dwpointdwpoint Posts: 9Questions: 3Answers: 0

    @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?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    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?

    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.

    My task is simply such that each Ajax request will have different columns. Do you understand?

    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

Sign In or Register to comment.