[英]how to solve Ajax post request show 500 (Internal Server Error) in laravel
In my project i want to store data in to database using ajax but when i submit the post request it show the error like (500 (Internal Server Error)) i google it several time but still same issue this is my ajax code 在我的项目中,我想使用ajax将数据存储到数据库中,但是当我提交发布请求时,它显示类似(500(Internal Server Error))的错误,我在Google上搜索了好几次,但是仍然存在相同的问题,这是我的Ajax代码
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form-insert').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data:{
_token: '{!! csrf_token() !!}',
data
},
dataType: 'json',
success:function(data){
console.log(data)
}
})
})
this is my view 这是我的看法
<form method="post" id="form-insert" action="{{ URL::to('item/store')}}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="text">Email address:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="contact_no">Contact No:</label>
<input type="text" class="form-control" name="contact_no">
</div>
<button type="submit" class="btn btn-primary pull-right" id="add">Submit</button>
</form>
this is my route 这是我的路线
Route::post('/item/store', 'AjaxCrudController@store');
this is my controller 这是我的控制器
public function store(Request $request)
{
if($request->ajax()){
$item = AjaxCrud::create($request->all());
return response($item);
//return response($request->all());
}
}
You are trying to insert the data you are submitting in your ajax request: 您正在尝试将要提交的数据插入到ajax请求中:
data:{
_token: '{!! csrf_token() !!}',
data
}
That means that you are trying to create an AjaxCrud
resource containing two keys: _token
and data
. 这意味着您正在尝试创建一个包含两个键的AjaxCrud
资源: _token
和data
。 I suppose that you just want to store the data contained into the data
object, that is your serialized form and should contain a name
attribute. 我想您只想存储包含在data
对象中的data
,即您的序列化表格,应包含name
属性。
So you have multiple solutions, the first one is to create your AjaxCrud resource from the data object: 因此,您有多种解决方案,第一种是从数据对象创建AjaxCrud资源:
$item = AjaxCrud::create($request->get('data'));
The other solution is to send only the data you want in your ajaxRequest, and set your CSRF token into the headers of your request. 另一种解决方案是仅在ajaxRequest中发送所需的数据,并将CSRF令牌设置为请求的标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.