My datatable is working fine, all the features like pagination, sorting, searching are working with static table data content. But when I fetch data from database and render in datatable features like pagination, sorting, searching and other CSS are not working.
My view page code::
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#example').DataTable();
fetchproduct();
function fetchproduct() {
$.ajax({
type: "GET",
url: "/fetchproducts",
dataType: "json",
success: function(response) {
$('tbody').html("");
$.each(response.products, function(key, item) {
$('tbody').append('<tr>\
<td>' + item.id + '</td>\
<td>' + item.name + '</td>\
<td> <img src="images/' + item.image_path + '"> </td>\
<td><button type="button" value="' + item.id + '" class="btn btn-primary editbtn btn-sm">Edit</button></td>\
<td><button type="button" value="' + item.id + '" class="btn btn-danger deletebtn btn-sm">Delete</button></td>\
\</tr>');
});
}
});
}
});
<div class="table-responsive">
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Index</th>
<th>Name</th>
<th data-orderable="false">Image</th>
<th data-orderable="false">Edit</th>
<th data-orderable="false">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Index</th>
<th>Name</th>
<th>Image</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
</div>
Controller code and route::
public function fetchproduct()
{
$products = Product::all();
return response()->json([
'products'=>$products,
]);
}
// route
Route::get('products', [ProductController::class, 'index'])->name('products.index');
Route::post('products', [ProductController::class, 'store'])->name('products.store');
Route::get('fetchproducts', [ProductController::class, 'fetchproduct']);
When I load the datatable, all the data is rendered at once. Pagination feature is not working. Also sorting and searching are also not working. Why is it so?
$('tbody').append(response.products.map(item => `<tr> <td>${item.id}</td> <td>${item.name}</td> <td> <img src="images/${item.image_path}"> </td> <td><button type="button" value="${item.id}" class="btn btn-primary editbtn btn-sm">Edit</button></td> <td> <button type="button" value="${item.id}" class="btn btn-danger deletebtn btn-sm">Delete</button></td> </tr>`).join(''));and then delegate the button clicks from the tbody