Friday, March 3, 2017

Laravel form post with ajax

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..



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?



via Emiel Schumacher

Advertisement