我试图通过ajax为我的Laravel应用程序提交我的3页表单中的第一步,并且我已将其设置为当此次提交的验证失败时,它将返回验证错误但是它仍然继续进行表单处理的下一步。我到底做错了什么呢?我知道,当ajax响应中存在错误时,我没有做任何事情,但为什么如果出现错误,它仍然会在成功中做些什么。它先检查错误然后检查成功吗?
/*
* Create User After they complete the first part of the form.
*
*/
public function createUserFromOrder(Request $request)
{
$validation = $this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirm|unique:users,email',
'email_confirmation' => 'required'
]);
if ($validation->fails()) {
return Response()::json([
'success' => false,
'errors' => $validation->errors()->toArray()
], 200);
}
$randomPassword = str_random(7);
$createdSuccessfully = "<div class='alert alert-success' role='alert'><span class='status-available'> User Profile Created.</span></div>";
$userData = [
'email' => $request->email,
'password' => $randomPassword,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
];
$user = Sentinel::registerAndActivate($userData);
$role = Sentinel::findRoleByName('patient');
$role->users()->attach($user);
Sentinel::login($user, true);
$order = Order::create([
'program_id' => $request->program_id,
'program_type_id' => $request->program_type_id,
'amount' => 433,
'order_type' => 0,
'paid' => 0,
'status' => 0
]);
$user->complete($order);
$order->addAddon($request->input('addons'));
return $createdSuccessfully;
}
$.ajax({
type: "POST",
url: '{{action('OrderProcessController@createUserFromOrder') }}',
data:
{
email: email,
first_name: first_name,
last_name: last_name,
program_id: program_id,
program_type_id: program_type_id,
amount: amount,
addons: addons
},
success:function(data){
$("#user-created-confirmation").html(data);
},
error:function (){}
}, function(){
setTimeout(function() {
})
});
答案 0 :(得分:1)
我相信这是因为你可能误解了.ajax()的“成功”属性 它只是意味着AJAX请求成功,而不是天气你的表单通过验证。您应该将错误处理函数放在成功函数中,如下所示:
success:function(data){
if(AreThereErrors() == false) {
$("#user-created-confirmation").html(data);
} else {
HandleErrors();
}
},
答案 1 :(得分:0)
如果您的状态代码不是200
,则会调用error
ajax调用块。尝试在那里执行你的代码。
例如:
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
console.log(err);
}