0
votes

I want to post a form with ajax. I get a errror in my console:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

I have a form:

{!! Form::open(array('url'=>'uren','method'=>'POST', 'id'=>'myform')) !!}
//inputs here etc..
{{ Form::button('Add', array('class' => 'btn btn-btn send-btn')) }}
{{ Form::close() }}

My Ajax:

$(document).ready(function(){
    $('.send-btn').click(function(){
        $.ajax({
            url: 'uren',
            type: "post",
            data: {
                'werk':             $('input[name="werk"]').val(),
                'starttijd':        $('input[name="starttijd"]').val(),
                'eindtijd':         $('input[name="eindtijd"]').val(),
                'omschrijving':     $('input[name="omschrijving"]').val(),
                '_token':           $('input[name="_token"]').val()},
            success: function(data){
                alert(data);
            }
        });
    });
});

In route(web.php):

Route::post('uren', 'User\UrenController@store');

In controller:

public function store() {

    if (\Request::ajax()) {

        if(Request::input('omschrijving') != '') {
            $omschrijving = Request::input('omschrijving');
        }else{
            $omschrijving = '';
        }

        DB::table('uren')->insert(
            [
                'userID' => Auth::user()->id,
                'datum' => Carbon\Carbon::now(),
                'projectID' => Request::input('werk'),
                'starttijd' => Request::input('starttijd'),
                'eindtijd' => Request::input('eindtijd'),
                'omschrijving' => $omschrijving
            ]
        );

    }

}

I think I need to do something with the csrf_token token. To pass the 500 error. But how can I do that?

[UPDATE] I added the token and I can send the token back and show the token in a alert. But when I add DB::table.... it still gives me the 500 error

[COMPLETE] The problem was my query.. a field was empty but it needs to be a string. I solved it.

1
Thanks for your answers. I have now the token in my codes. I can alert the token that has been send to my controller with the Ajax request. But I still get the 500 error when I add the DB::table code - user7429559
Just FYI, your if statement (Request::input('omschrijving') != '') is pointless. Your checking if the request input is an empty string and if it is then make your $omschrijving an empty string anyway. Also you can supply a default to Request::input() as the second param i.e. 'omschrijving' => Request::input('omschrijving', '') - Rwd

1 Answers

0
votes

If you dont want CSFR middleware you can disable that in laravel 5:

To disable CSFR protection: go to this file:

   app/Http/Middleware/VerifyCsrfToken.php

You can disable for all post request or for particular route. For more info xfer: https://laravel.com/docs/5.0/routing#csrf-protection

OR

just pass another parameter in your data "_token": "{{ csrf_token() }}",