0

I am trying to use datatables of jquery to create a table with fetched members from database. This is my html and javascript code:

<table id="workerTable" class="table-bordered table-hover" width="80%" cellspacing="0">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Role</th>
                <th>Dep_id</th>
                <th>Start_Date</th>
                <th>Updated</th>
            </tr>
        </thead>
    </table>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#workerTable').DataTable( {
                "processing": true,
                "serverSide": true,
                "ajax": {{ URL::route('workerData') }}
            } );
        } );
    </script> 

I have this route defined:

Route::get('/workers/data' , 'WorkersController@fetch')->name('workerData');

And the function fetch() inside the WorkersController is like that:

public function fetch()
    {
        $workers = Worker::all();
        echo json_encode($workers);
    }

I am new to laravel and I think I am not understanding it well. Is the call to this line

"ajax": {{ URL::route('workerData') }}

make the route to call the fetch function of the WorkersController ?

3
  • Assuming the output is a string, you probably need to wrap quotes around it: "ajax": '{{ URL::route('workerData') }}' Commented Sep 9, 2017 at 15:53
  • I did that but still nothing changed. Commented Sep 9, 2017 at 15:54
  • return $workers->toJson() in the fetch method Commented Sep 9, 2017 at 16:02

1 Answer 1

1

You should use this package if you're not already using it: https://github.com/yajra/laravel-datatables

Then replace
"ajax": {{ URL::route('workerData') }}
by
"ajax": {{ route('workerData') }}

And here's the correction for your function

use App\Worker;
use Yajra\Datatables\Datatables;

// ...

public function fetch()
{
    $workers = Worker::all();

    return Datatables::of($workers)->make(true);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I did what you said , but the ajax is returning the html page as a response instead of the database object
Try using this example and it should work: datatables.yajrabox.com/eloquent/basic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.