I am currently working on implementing a search function with DataTables, but I am facing issues with filtering the results from the table. Despite going through the documentation, something seems to be off.
I am fetching data using an AJAX call for this functionality.
The HTML snippet includes the search input field along with the accompanying jQuery code, but I am unable to identify what's missing in my implementation.
There are no error messages being displayed; however, the table data is not getting filtered as expected.
HTML
<div class="row d-flex align-items-end flex-column">
<div class="col-sm-12 col-lg-4">
<input type="text" class="form-control" id="myInput" placeholder="Search">
</div>
</div>
<table id="tblData" class="table table-striped tabled-bordered" style="width: 100%">
<thead>
<tr>
<th>Term</th>
<th>Course Title</th>
<th>Class No</th>
<th>Session</th>
</tr>
</thead>
</table>
jQuery
//DataTables
$(document).ready(function() {
$.fn.loadDataGrid = function() {
$('#tblData').DataTable({
orderCellsTop: true,
fixedHeader: true,
pageLength: 10,
responsive: true,
dom: 'tip',
columnDefs: [
{
targets: [0],
sortable: true,
data: 'semester',
width: '10%'
},{
targets: [1],
sortable: false,
data: 'title',
width: '10%',
},{
targets: [2],
sortable: false,
data: 'class_nbr',
width: '10%',
className: 'dt-head-center dt-body-center'
},{
targets: [3],
sortable: false,
data: 'session',
width: '10%',
className: 'dt-head-center dt-body-center'
}],
order: [0, 'desc'],
ajax: {
url: 'data/ajax/file.cfm',
dataSrc: '',
error: function(xhr, error, code) {
$().showMsgInfo('Sorry, there was a problem trying to retrieve the data. Please try again later.');
}
},
});
});
//search function
$(document).ready(function() {
var table = $('#tblData').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
table.search( this.value ).draw();
});
});