I have this ajax request in home.blade.php
:
function send(event) {
event.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
type: "POST",
url: "{{ route('add_action') }}",
data: {name: $("#name").val(), niceness: $("#niceness").val(), _token: "{{ Session::token() }}"}
});
}
in the controller I have this postAction:
public function postInsertNiceAction(Request $request)
{
$this->validate($request, [
'name' => 'required|alpha|unique:nice_actions',
'niceness' => 'required|numeric',
]);
$action = new NiceAction();
$action->name = ucfirst(strtolower($request['name']));
$action->niceness = $request['niceness'];
$action->save();
$actions = NiceAction:: all();
if ($request->ajax()) {
return response()->json();
}
return redirect()->route('home');
}
I added this meta tag:
<meta name="_token" content="{{ csrf_token() }}">
so when I run this I got this error :
jquery-1.12.0.min.js:4 POST http://localhost:8000/do/add_action 422 (Unprocessable Entity)
I tried to change the version of the jQuery file but it's not working.
Any help will be appreciated!
I'm new to Laravel.
Thank you
Try this:
function send(event) {
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
$.ajax({
type: "POST",
url: "{{ route('add_action') }}",
data: { name: $("#name").val(), niceness: $("#niceness").val() },
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.