[英]My Ajax keeps returning 419 and 500 error status
I'm making a form that's called by Ajax and trying to configure the form to submit using Ajax. 我正在制作一个由Ajax调用的表单,并尝试将表单配置为使用Ajax提交。 This form is supposed to submit the data through route('ruangrapat.store). 这个表单应该通过route('ruangrapat.store)提交数据。 But every time I submit the form, it returns 419 status when I don't use csrf_token() in Ajax and if I use the csrf_token() in Ajax. 但是每次我提交表单时,如果我在Ajax中不使用csrf_token()并且在Ajax中使用csrf_token(),它将返回419状态。 It always returns 500 internal server error. 它总是返回500内部服务器错误。 Can someone help me to solve this problem? 有人可以帮我解决这个问题吗? I've been reading almost every discussion that I found on the internet, but still no answer. 我几乎每次都在阅读我在互联网上发现的所有讨论,但仍然没有答案。
Maybe I missed something important on my code. 也许我错过了一些重要的代码。 Please review my code. 请查看我的代码。
//ajax
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();//should i do this??
//if i should take the value of inputs 1 by 1,please show me the proper way
var token="{!!csrf_token()!!}"
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
success:function(result){
$('#result').html(result);
}
});
});
});
//controller
public function store(Request $request)
{
$data = new Ruangrapat();
...
$data->contact = $request->get('contact');
$data->save();
return view('ajax-result.ruangrapat.index')->with('status', 'Ruang rapat baru berhasil ditambahkan!');
//is this return value correct??
}
//route
Route::resource('ruangrapat', 'RuangrapatController');
我有同样的问题,419与csrf令牌匹配,当你修复它时,请求转到服务器所以,内部服务器错误500说存储时有问题,所以重新查看控制器中的存储功能和确保函数中的所有过程都正确。
To make any ajax request, it is recommended to add the CSRF token to the header of the ajax requests 要发出任何ajax请求,建议将CSRF令牌添加到ajax请求的标头中
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
As advised by laravel documentation 正如laravel文档所述
To see what the ajax request is sent, I would advise having the controller return the data to you and see it through the web console. 要查看ajax请求的发送内容,我建议让控制器将数据返回给您并通过Web控制台查看。
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();
var token="{!!csrf_token()!!}";
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
dataType:'JSON',
//You can use sucess or done, personally i like more done
}).done(function (data) {
console.log(data)
});
});
});
And in the controller 并在控制器中
public function store(Request $request)
{
return response()->json($request->input());
}
Other option is to use the network monitor of the browsers and see the variables that are sent. 其他选项是使用浏览器的网络监视器并查看发送的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.