김정명 김정명 - 15 days ago 5
Javascript Question

laravel ajax validation how to make if it's failed?

I want to make if any values are nothing, show error message box.

if($validator->passes())
is working successfully, but I have troubles in
if its failed
.
console.log(res)
brings nothing. How can I solve this problem?
i have tried
$errors = $validator->errors();
$errors = json_decode($errors);


Js

$.ajax({
url: url,
type: 'POST',
data: $writeForm.serialize(),
error: function(res){
if (!res.status) {

console.log(res.message);
var error = $.parseJSON(res.message);
$('div.visitor-form > div.alert').html(error);

}
}

});


controller

$validator = validator::make($data = Input::all(), mypage::$rules);
if($validator->fails()) {

$response = array();
$response['status'] = false;

$errors = $validator->getMessageBag()->toArray();
$response['message'] = $errors;

return response()->json($response);

}

Answer
$response['errors'] = $validator->errors()->all();

return response()->json($response, 400);

The browser needs to know the error status in order to trigger your error method in that ajax function. See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error

 $.ajax({
        url: url,
        type: 'POST',
        data: $writeForm.serialize(),
        error: function(res){ //by using this method, you're assuming that all the logic here is for error handling.
                console.log(res.status, res.errors);
        }

    });