Custom addParam and deleteParam plugins with DT 2.0
Custom addParam and deleteParam plugins with DT 2.0
Loren Maxwell
Posts: 387Questions: 94Answers: 10
The following two custom plugins don't seem to work with DT 2.0:
/**
* Add a parameter to the current Ajax data.
*
* @params {object} Parameter(s) to add.
* @returns {DataTables.Api} this
*/
$.fn.dataTable.Api.register( 'ajax.addParam()', function ( params ) {
return this.iterator( 'table', function ( settings ) {
/* Note settings.ajax.data here */
$.extend(settings.ajax.data, params);
});
});
/**
* Delete a parameter from the current Ajax data.
*
* @paramKey {string} Parameter key to delete.
* @returns {DataTables.Api} this
*/
$.fn.dataTable.Api.register( 'ajax.deleteParam()', function ( paramKey ) {
return this.iterator( 'table', function ( settings ) {
/* Note settings.ajax.data here */
delete settings.ajax.data[paramKey]
});
});
Here's an example of how it should work:
console.log(datatable.ajax.params())
// Output: {breakfast: 'Burritos!'}
datatable.ajax.deleteParam('breakfast')
console.log(datatable.ajax.params())
// Output: {}
datatable.ajax.addParam({
lunch: 'Tacos!'
})
console.log(datatable.ajax.params())
// Output: {lunch: 'Tacos!'}
Perhaps I should be referencing something other than settings.ajax.data
now?
For reference, the full discussion from 2018 is here:
https://datatables.net/forums/discussion/comment/125460/#Comment_125460
This question has an accepted answers - jump to answer
Answers
Oops! Never mind -- the error was mine! It's working!
That's a neat set of plugins!
Kevin
Thanks, @kthorngren!
It could be a little more robust (such as accepting arrays) but it works for what I need it to do!
Comment removed!
Thanks, Kevin -- I realized my error and removed the comment before anyone saw it!
Or so I thought I had!
That's ok, I've done the same
Kevin
Another update for the plugin.
If there is no
ajax.data
object then the$.extend(settings.ajax.data, params);
won't have anything to extend. This could happen ifsettings.ajax
is only a string or null.This checks to see if either situation exists and then changes
settings.ajax
into an object with thedata
member:Complete code: