如果已在laravel 5中收到电子邮件,我正在尝试在ajax中进行验证。
这是我的ajax:
$.ajax({
type: 'POST',
url: '/EditEmail',
data: form.serialize(),
dataType: 'json',
timeout: 9000,
error:function(data) {
//verify if the user has already been taken
},
success:function(data) {
window.location.href=window.location.href;
}
});
这是我的控制器中的代码:
public function EditEmail()
{
if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
{
DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));
return Response::json(['success' => 'request succeeded'], 200);
}
}
所以我已经在我的控制器中进行验证,用户无法引入相同的电子邮件,但我想知道如何将数据从我的控制器发送到ajax,以便我也可以在那里进行验证。是否有人有解决方案?
答案 0 :(得分:1)
您有两种选择。
使用statusCode的第一个选项:
根据Ajax文档(http://api.jquery.com/jQuery.ajax/),您可以这样做:
statusCode: {
200: function() {
alert( "user found" );
},
404: function() {
alert( "user not found" );
}
}
并在您的控制器中返回:
// user does not exist
return Response::json(['status' => 'not_found'], 404);
//or if the user does exist
return Response::json(['status' => 'found'], 200);
使用简单json数据的第二个选项:
$.ajax({
type: 'POST',
url: '/EditEmail',
data: form.serialize(),
dataType: 'json',
timeout: 9000,
error:function(data) {
//something went wrong with the request
},
success:function(data) {
if(data['status'] == "found") {
alert( "user found" );
} else {
alert( "user not found" );
}
}
});
并在您的控制器中:
public function EditEmail()
{
if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
{
DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));
return Response::json(['status' => 'not_found']);
}
return Response::json(['status' => 'found']);
}