Soer.05
Soer.05

Reputation: 33

laravel 5 ajax, keep get 500 internal erro with csrf token

I want to make a search program to get data from huge data table. User can search data from to column, code/kode and name (every data have 1 code/kode). If a user click search button, using AJAX, send request to server, then the client get result and display it at the table.

Here the my view :

<div class="modal-body">
    <div class="form-inline form-inline" style="margin-bottom: 10px">
         {!! Form::select('jenis-select',['Kode BU','Nama BU'],null,['class' => 'form-control']) !!}
         {!! Form::text('value-select','',['class' => 'form-control']) !!}
         <button type="button" id="cari-bu" class="btn btn-default">Cari</button>
    </div>
    <table class="table">
        <thead>
            <tr>
                <th>Kode BU</th>
                <th>Nama BU</th>
            </tr>
        </thead>
        <tbody id="hasil-cari"></tbody>
    </table>
</div>

The result of search will display on <tbody> with attribut id="hasil-cari"
this is my ajax :

$(document).ready(function () {
    $.ajaxSetup({
        headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
    });
    $('#cari-bu').click(function () {
        $.ajax({
            url: 'select_bu',
            type: 'post',
            data: {'_token': $('input[name=_token]').val(),
                'jenis': $('select[name=jenis-select]').val(),
                'value': $('input[name=value-select]').val()
            },
            success: function (data) {
                $('#hasil-cari').html(data);
            }
        });
    });
});

And this is the controller that handle AJAX:

public function postSelect() {
        if (Request::ajax()) {
            $input = Input::all();
            if ($input['jenis'] == 0) {
                $hasil = Daftarbu::where('kodebu', $input['value'])->get();
            } elseif ($input['jenis'] == 1) {
                $hasil = Daftarbu::where('namabu','LIKE','%'.$input['value'].'%')->get();
            }
            $hasilAkh = '<tr>';
            foreach ($hasil as $dHasil){
                $hasilAkh .= '<td>'.$dHasil->kodebu.'</td><td>'.$dHasil->namabu.'</td>';
            }
            $hasilAkh .= '</tr>';
            return $hasilAkh;
        }
    }

My route:

Route::post('select_bu','Pelayanan@postSelect');

I have put this meta at <head> tag

<meta name="_token" content="{!! csrf_token() !!}"/>

With that code I keep get 500 internal error. Can anyone find the problem ?

Upvotes: 2

Views: 285

Answers (2)

Justin Origin Broadband
Justin Origin Broadband

Reputation: 1520

In your routes.php

    Route::post('/select_bu',['as'=>'select_bu','uses'=>'Pelayanan@postSelect']);

In your Javascript:

    $(document).ready(function () {

        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name="_token"]').attr('content')}
        });

        $('#cari-bu').click(function () {
            $.ajax({
                url: '{!! route('select_bu') !!}',
                type: 'post',
                data: 'jenis': $('select[name="jenis-select"]').val(),
                      'value': $('input[name="value-select"]').val()
                },
                success: function (data) {
                    $('#hasil-cari').html(data);
                }
            });
        });
    });

The $.ajaxSetup({}) you have loads the token into your ajax setup. There's no need to include it as part of your <form> or as a param for sending as part of your ajax object key-pairs to send on the request. Most likely the error occurred due to the two _token values conflicting with each other once they reached the VerifyCsrfToken Middleware, seeing as the _token referenced by $('input[name=_token]') doesn't seem to get matched?

On that note, the selectors should be written:

    $('input[name="_token"]')

I have corrected this in the code I've supplied.

For more information:

https://laravel.com/docs/5.2/routing#named-routes

https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

https://api.jquery.com/attribute-equals-selector/

Upvotes: 1

Jonathan
Jonathan

Reputation: 11494

Dump out your routes.php, it may be that you have somehow managed to avoid loading the web middleware that includes CSRF checking.

In 5.2 only the maintenance middleware is executed on every request. Everything else like cookies, sessions, and CSRF has been moved into the web middleware group.

You may need something like:

Route::group(['middleware' => 'web'], function () {
    // ...
});

Also, run and dump out for us your generated routes php artisan route:list and show those results as well.

Lastly, can you double check your HTML form is actually well-formed (no pun intended). You might not have any opening form tag e.g.:

{!! Form::open(['url' => 'foo/bar', 'method' => 'post']) !!}
    {{-- Form::select --}}
{!! Form::close() }}

Relevant documentation for Form, if not mistaken.

Upvotes: 0

Related Questions