Search code examples
phpjsonlaravelcsrfjquery-jtable

How to fix CSRF TOKEN ERROR while fetching data to Jtable in laravel


I am using Jtable in laravel but facing CSRF TOKEN ERROR on it. How to add csrftokenValue in my Post function ?

My route look like this:

Route::post('test_list', function() {
$tests = LabTest::all()->toArray();
$result = array(
    'Result' => 'OK',
    'Records' => $tests
);
return $result;
});
Route::post('/test_create', function() {
    LabTest::create(array(
        'Name' => Input::get('Name'),
        'Remark' => Input::get('Remark'),
    ));
    $result = array(
        'Result' => 'OK',
        'Records' => Input::all()
    );
    return $result;

Solution

  • Looks like you are using ajax. If you are using jquery for ajax request, then you might want to include X-CSRF-TOKEN in those requests.

    Add a meta tag for laravel token

    <meta name="csrf-token" content="{{ csrf_token() }}">
    

    And set jquery ajax properties to use the above.

    <script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>
    

    Take a look at Laravel docs