Wasif Khalil Wasif Khalil - 1 year ago 101
Ajax Question

Sending Custom Data from Custom Select field in Datatables

i have created a custom select field into my datatable

html = '<div class="col-md-3"><select id="filterleads" class="filterleads form-control">';
html += '<option value="all">All Leads</option>';
html += '<option value="processed">Processed Leads</option>';
html += '<option value="unprocessed">Unprocessed Leads</option>';
html += '</select></div>';


which looks like this
enter image description here

now when the select changes i want it to send its value with the datatable ajax so i can filter records according to that

this is how im doing this

var table = $('#allleadstable').DataTable( {
"processing": true,
"serverSide": true,
"responsive": true,
"iDisplayLength": 50,
"sScrollX": "100%",
"order": [[ 1, "desc" ]],
"sScrollXInner": "100%",
"bScrollCollapse": true,
"ajax": {
data: {
"leadfilter": ($("#filterleads").val() ? $("#filterleads").val() : 'all')
"scrollCollapse": true,
//"sDom": '<"top"flip>rt<"bottom"flip><"clear">',
"dom": '<"toolbar">frtip',
columnDefs: [
{ width: 60, targets: 0 },
{ width: 50, targets: 1 },
{ width: 50, targets: 2 },
{ width: 150, targets: 3 },
{ width: 150, targets: 4 },
{ width: 100, targets: 5 },
//{ width: 100, targets: 7 },
{ width: 100, targets: 6 }

$(document).on("change", "#filterleads", function(event) {

the problem is that it doesnt find $("#filterleads") and always send the value 'all' even when i change the select

how do i send its value everytime i change select?

Answer Source

The issue is because you only read the value of your select when the page loads, and it's all by default. You need to change your code so that it reads the value of the select when it makes the request. To do this provide a function to the data property:

"ajax": {
    url: "/leads",
    data: function(data) {
        data.leadfilter = $("#filterleads").val()

Note that I removed the ternary as it's not needed. The select will always have a value.

For more information see the ajax.data entry in the DataTables documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download