简体   繁体   中英

Cannot call the function inside a controller from the javascript in laravel

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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM