user633440
user633440

Reputation:

Load/Save sorting & filter options on DataTables using Laravel

I need to save the state of pagination, sorting & search inputs, ultimately utilizing Laravel and an API instead of the database. I'd rather not use yajra/laravel-datatables as I've already created the complex DataTable I need.

Example

<script type="text/javascript">
    $(document).ready(function () {
        var table = $('#stackoverflow-datatable').DataTable({
            "stateSave": true,
            "stateSaveCallback": function (settings, data) {
                $.ajax({
                    "url": "/api/save_state",
                    "data": data,
                    "dataType": "json",
                    "success": function (response) {}
                });
            },
            "stateLoadCallback": function (settings) {
                var o;
                $.ajax({
                    "url": "/api/load_state",
                    "async": false,
                    "dataType": "json",
                    "success": function (json) { o = json; }
                });
                return o;
            }
        });
    });
</script>

The URLs: "/api/load_state" point to a Laravel route, and the routes point to specific methods on the Controller. I see that it's calling the methods correctly. However, I don't know what it's sending me or how I change the JS to tell it to give me what I need. Once I have an on Object (or something), send it back and apply it when the user goes back to the page.

Upvotes: 2

Views: 1603

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87779

By the description, looks like you have everything working, you just need a way to debug data you are receive, so you can use Log to do that:

Route::get('/api/load_state', function() {
    \Log::info(app('request')->all());
});

And tail the log

tail -f storage/logs/laravel.log

So if you hit

http://domain.dev/api/load_state?what=1    

You should see

enter image description here

To respond a json object back to the client, you can do

Route::get('/api/load_state', function(Request $request) {
    return response()->json(
        User::find($request->get('user_id'))
    );
});

Upvotes: 1

Related Questions