Filter data from ajax request before passing it to DataTables
Filter data from ajax request before passing it to DataTables
Hello all!
I need to filter data recieved from ajax request before putting it to DataTables, therefore I can not use DataTables Api.ajax() method. Also, I'd like to avoid reinitialization DT each time after jQuery.ajax() request.
My question: how can I initialize DT once and then only refresh it with new portions of data?
Now I can do it only destroying previously initialized table and initialize it again with fresh data filtered after ajax request.
Workflow now is as follows:
1. $.ajax()
2. Filtering
3. (Re)initialize and draw table
Desirable workflow should consist of first initialization of DT table and then going through the cycle
1. $.ajax()
2. Filtering
3. Redraw table
Answers
In the
success
function of your $.ajax() request you can use$.fn.dataTable.isDataTable()
to determine if the Datatable has been initialized. If not initialize normally. You can useclear()
androws.add()
to clear and add the rows to the table. Oh, and don't forgetdraw()
Kevin
Thank you, Kevin.
Previously when no filtering was needed I could fetch ajax data via DT itself:
My init section was like follows:
Then I refreshed table using only this portion of code without reinitialization:
I don't know how can I pass the filtered data the same way.
It could be like this:
When you listed
$.ajax()
I thought you were using jQuery ajax() to fetch the data. If you want to start with a blank Datatable I would recommend using jQuery ajax(). Then follow the steps I outlined above.You are accessing the Datatables configuration object directly which is not recommended as this object can change at anytime. I'm not sure this will work.
If you prefer to use the
ajax
option then I suggest initializing Datatables with this option then send a parameter that causes your server script to return an empty dateset, ie, an empty array.You can use
ajax.data
as a function for dynamic parameters. I'm not sure how usingthis.clientNameTable.ajax.url(this.nameListUri).load();
will affect using a function forajax.data
.Kevin
Well, I got it, Kevin!
Thank you!