Wasif Khalil Wasif Khalil - 4 months ago 23
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>';

$("div.toolbar").html(html);


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": {
url:"/leads",
data: {
"leadfilter": ($("#filterleads").val() ? $("#filterleads").val() : 'all')
}
},
"scrollX":true,
"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) {
table.ajax.reload();
});


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

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.