[英]Laravel validation errors are being displayed in Ajax Success Event
When I submit an Ajax request and I know that the data should fail, I am receiving the error response within the success
event instead of the fail
event.当我提交 Ajax 请求并且我知道数据应该失败时,我在
success
事件而不是fail
事件中收到错误响应。
I need the response from Laravel to be sent to the Ajax fail event, as I will be building custom functionality for when the request fails to process.我需要将来自 Laravel 的响应发送到 Ajax 失败事件,因为我将在请求处理失败时构建自定义功能。
I've tried all sorts to try and get it to work, but I'm at a complete loss as to why it's returning into the Success event.我已经尝试了各种尝试让它工作,但我完全不知道为什么它会回到成功事件中。 I must be being daft or something!
我一定是傻了还是什么的!
My Function within the Controller:我在控制器中的功能:
public function add_company(Request $request)
{
/**
* Validate the Add Company request
*/
$validator = \Validator::make($request->all(), [
'name' => 'required',
'sector' => 'required',
'number' => 'required',
'email' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => 'Something went wrong']);
}
DB::table('companies')->insert([
'user_id' => Auth::id(),
'company_number' => $request->company_number,
'name' => $request->name,
'sector' => $request->sector,
'number' => $request->number,
'email' => $request->email,
'address_1' => $request->address_line_1,
'address_2' => $request->address_line_2,
'city' => $request->city,
'postcode' => $request->postcode,
]);
return response()->json(['success' => 'Company created successfully.']);
}
My Ajax function:我的 Ajax 函数:
$('[data-add-company]').on('submit', function(e) {
e.preventDefault();
let $this = $(this);
let action = $this.attr('action');
let method = $this.attr('method');
var formData = $this.serialize();
$.ajax({
type: method,
url: action,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Access-Control-Allow-Origin': '*',
},
data: formData,
success: function(data){
console.log('success');
console.log(data); // Fail messages appear here for some reason.
},
error: function(data) {
console.log('error');
console.log(data);
},
});
});
I've tried using data.success
and data.error
to get the correct message but they just come up as undefined when I key into them.我已经尝试使用
data.success
和data.error
来获取正确的消息,但是当我输入它们时,它们只是未定义。
What should happen应该发生什么
fail
event should initiate when the validation fails and show the correct fail message from the controller.fail
事件应该启动。success
event should only contain the success message from the controller, once the request has been successfully validated.success
事件应该只包含来自控制器的成功消息。 Thanks in advance!提前致谢!
What seems to be happening is even though your request failed its validation in the controller its still returns a valid response which JQuery sees as a success
, allowing it into the success
callback on the frontend.似乎正在发生的事情是,即使您的请求在控制器中的验证失败,它仍然返回一个有效的响应,JQuery 将其视为
success
,允许它进入前端的success
回调。
Try尝试
if ($validator->fails()) {
return response()->json(["error" => "something went wrong"], 422);
}
This should trigger the error callback.这应该会触发错误回调。
You can also pass the errors back like this:您还可以像这样将错误传回:
return response()->json($validator->errors(), 422);
To get all the error messages on the frontend.获取前端的所有错误消息。
For further reading check out this jQuery error handling article .如需进一步阅读,请查看这篇 jQuery错误处理文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.