I am in a little bind, I am trying to validate my form from jquery and link the validation with laravel validator. I would like to know how to pull back a JSON response with the laravel errors in jquery or javascript.
Can someone point me in the right direction
Here is the code for my controller store method
public function Postdata(PostRequest $request) {
try {
$input = $request->all();
$task = Task::create($input);
return Response::json([ 'response'=>'success', 'data'=>$task ]);
} catch (Exception $e) {
return Response::json([ 'errors'=> [ ['message' => $e->getMessage()] ] ]);
}
}
and my jquery
` $("#from").submit(function(event) {
$.ajax({
type: 'post',
url: '/myproperties/save',
data: { '_token': token, 'data': "good" },
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
// Render the errors with js ...
}
});
});
`
Thanks please help
You can try the Validation method from laravel
public function Postdata(PostRequest $request) {
try {
$input = $request->all();
$validator = \Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return Response::json([ 'response'=>'error', $validator->errors()->all()]);
}
$task = Task::create($input);
return Response::json([ 'response'=>'success', 'data'=>$task ]);
} catch (Exception $e) {
return Response::json([ 'errors'=> [ ['message' => $e->getMessage()] ] ]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.