Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To update the Laravel Backpack Datatable through ajax when there is a change in the select field, follow these steps:

  1. Create a select field in your view with the onchange event:
<select id="category" onchange="getData()">
    <option value="">Select Category</option>
    <option value="1">Category 1</option>
    <option value="2">Category 2</option>
    <option value="3">Category 3</option>
</select>
  1. Add a javascript function that sends an ajax request when the value of the select field changes:
function getData() {
    var category = $('#category').val();
    var url = '/getData'; // URL of the controller function that returns the data

    $.ajax({
        url: url,
        type: 'POST',
        data: {category: category},
        success: function (data) {
            $('#datatable').DataTable().ajax.reload();
        },
        error: function (data) {
            console.log('Error:', data);
        }
    });
}
  1. Create a controller function that returns the filtered data:
public function getData(Request $request) {
    $category = $request->category;

    $data = DB::table('table_name')->where('category', $category)->get();

    return response()->json(['data' => $data]);
}
  1. In the Backpack Datatable configuration file, add an ajax section that specifies the URL of the controller function:
'ajax' => [
    'url' => '/getData',
    'type' => 'POST',
    'data' => 'function(d) { d.category = $("#category").val(); }',
],

That's it! Now whenever the value of the select field changes, the datatable will be updated with the filtered data.