i am using Datatable 1.9.2 in my project. I am display a list of applicants in it via AJAX. There is also a filter form which is used to filter data. Everything is working fine, but the problem is that if i filter records and no data is returned by DB then datatable generates an error in POPUP. Can someone guide me how to handle empty ajax response with datatable, how to handle empty dataset.
Below is the code which i am using
$('#applicants_list').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "bootstrap",
"sDom": '<"H"Cfr>t<"F"ip>',
"oColVis": {
"activate": "mouseover",
"aiExclude": [ 10 ],
"sAlign": "left"
},
"bFilter": false,
"sAjaxSource": script.php,
"aoColumns": [
{"bSortable": true }, // attachments
{"bSortable": true }, //Subject Line
{"bSortable": true }, // Date Sent
{"bSortable": true }, // File Name
{"bSortable": false },
{"bSortable": false },
{"bSortable": true },
{"bSortable": true },
{"bSortable": true },
{"bSortable": false }
],
"aaSorting": [[0, 'desc']]
} );
Just return following data from server/ajax response when filter return record is empty it will display empty record message.
echo '{
"sEcho": 1,
"iTotalRecords": "0",
"iTotalDisplayRecords": "0",
"aaData": []
}';
echo json_encode(array('aaData'=>''));
works for me.
For those looking for an ASP.NET solution, here's an example using JSON.NET:
JObject jObj = new JObject(
new JProperty("draw", 0),
new JProperty("recordsTotal", 0),
new JProperty("recordsFiltered", 0),
new JProperty("data", new JArray())
);
return Content(jObj.ToString(Formatting.None), "application/json");
The parameters in the other answers here are for legacy versions of DataTables, I think it still might be backwards compatible with them though, at least aaData is handled from what I've seen in the code.
Try using defaultContent attribute per columns objects...
PD: Double quotes arent necessary
columns: [
{bSortable: true, defaultContent: '' }, // attachments
{bSortable: true, defaultContent: '' }, //Subject Line
{bSortable: true, defaultContent: '' }, // Date Sent
{bSortable: true, defaultContent: '' }, // File Name
{bSortable: false, defaultContent: '' },
{bSortable: false, defaultContent: '' },
{bSortable: true, defaultContent: '' },
{bSortable: true, defaultContent: '' },
{bSortable: true, defaultContent: '' },
{bSortable: false, defaultContent: '' }
],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With