Cannot Get Data to Add to Table After Initialization
Cannot Get Data to Add to Table After Initialization
I am attempting to populate a Datatable after it has been initialized based on the user choosing a particular record to edit.
I defined the table as such:
var oEventSchedulerDetailsTable = $('#eventtime_details').DataTable( {
info: false,
paging: false,
select: {
"info": false
},
"language": {
"emptyTable": "No times scheduled"
},
searching: false,
processing: true,
});
I then have a button defined that when clicked retrieves the ID I need to populate the table defined above:
$("#event_scheduler_table_menu .EditMenuButton").on("click", function(e) {
e.preventDefault();
if ($(this).hasClass('disabled')) {
return false;
}
var selectedRowData = oEventSchedulerTable.rows( { selected: true } ).data();
loadData(selectedRowData[0].id);
$('#editEvent').modal('toggle');
});
The loadData function is as follows:
function loadData(id) {
var dataString = "eventid=" + id;
$.ajax({
type: 'POST',
url: root + 'resources/php/data_handler_event_scheduler_details.php',
data: dataString,
dataType: 'json',
success: function(data) {
console.dir(data.data);
oEventSchedulerDetailsTable.clear().draw();
oEventSchedulerDetailsTable.rows.add(data).draw();
},
error: function(request, status, error) {
bootbox.alert(request.responseText);
}
});
}
So when I run my code, I can see in the browser inspector window that the data_handler_event_scheduler_details.php returns the json data, but the $('#eventtime_details').DataTable never shows the data in the table.
Any clues on what I am missing here?
This question has an accepted answers - jump to answer
Answers
Its hard to say without knowing what is returned. You have
console.dir(data.data);
but you are usingoEventSchedulerDetailsTable.rows.add(data).draw();
. Is your data in thedata.data
object or just indata
?Is it one row or multiple rows in an array. If its one row not in an array then you will use
row.add()
, note the singularrow
for one row that is not in an array.If you still need help please post the ajax response from the browser's network inspector.
Kevin
The ajax call to data_handler_event_scheduler_details.php can return one item or several items in the array. Depends on how many times have been scheduled. Here's what the call returns in one particular case:
On the html side:
Ok, I got it working by redefining the table as:
On the html side as:
And then the loadData function:
However, I guess in cases where only one record is in the array, I will need to call
oEventSchedulerDetailsTable.rows.add(data.data).draw()
in a different way?If the one row is in an array like this you will still use
rows.add()
:But if your one row is not in an array, like this then use
row.add()
:The docs for both API's have more details.
Kevin