Reputation: 3762
How can I refresh the datatable after loading a dynamic content from an Ajax request? The flow is this, 1. a button will be click and this button contains an ID 2. I'll use this ID to do an Ajax request to the server 3. The server will reply the record from the passed ID 4. I'll load clear the initialized datatable and load the new content from the Ajax 5. Show bootstrap modal.
Now my problem is the header column and the content row of the datatable does not fit as shown below
The weird thing about this is when I resize my browser the header column fits with the table content.
Below is my code for this
<table id="mytable" class="cell-border" cellspacing="0" width="100%">
<thead class="table-header">
<tr>
<th>Comptetitor Item ID</th>
<th>Competitor Seller</th>
<th>Competitor Title</th>
<th>Competitor Price</th>
<th>Competitor Quantity Sold</th>
<th>Competitor Listing Status</th>
</tr>
</thead>
</table>
table1 = $('#mytable').DataTable({
scrollY : "250px",
scrollCollapse : true,
fixedColumns : false,
paging : false,
searching : false,
bInfo : false,
bSort : false,
});
$(document).on("click", ".a_tag_link",function() {
var row_id = $(this).data("row_id");
$.ajax({
type:'GET',
url:'/ajax/server_process',
dataType: 'json',
data: {
_token: "{{ csrf_token() }}",
view_id: $(this).data("row_id")
},
beforeSend: function() {
$.blockUI({ baseZ: 9999 });
},
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
table1.rows.add(response.data).draw(true);
},
complete: function(){
$.unblockUI();
}
});
return false;
});
Kindly help me with this. I just want the column header content to fit the table content without the browser being resized.
Updates: The table is fixed when I remove the scrollY attribute. But the problem is that the content is very large and I need the table to have a fix height
Upvotes: 1
Views: 2119
Reputation: 11750
Try waiting for the modal to fully load, and then append the data. Probably, the datatable holder is not visible yet, and did not get its final dimensions:
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
setTimeout(function() {
table1.rows.add(response.data).draw(true);
},250);
},
You could also listen to modal's custom events, and draw the datatable when the modal has finished its animation:
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
table1.rows.add(response.data);
},
...
$('#myModal').on('shown.bs.modal', function (e) {
$('#mytable').DataTable().draw(true);
})
Upvotes: 2