laravel ajax request params yields null

Viewed 1406

I am new to laravel framework and started following the laravel tasks tutorial. I am trying to pass via ajax request the name of the task in order to save it in the database.

front end:

var taskdata= {
    "name": $("#new_task").val()
};

//console.log(JSON.stringify(taskdata));

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    processData: false,
    success: function(result) {
        alert("success");
    }
});

server side:

Route::post('/task', function (Request $request) {

    //die(var_dump($request->json("name")));

    $validator = Validator::make(json_decode($request->getContent(), true), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return redirect('/');
});
2 Answers
Related