// php
public function store(Request $request)
{
$validator = Validator::make( $request->all(),[
'first_name' => 'string',
'last_name' => 'string',
'phone_number' => ['string', 'max:14'],
'email' => 'email'
]);
if($validator->fails())
{
$response = "<div class='alert alert-danger'><ul>";
foreach($validator->errors()->all() as $error)
{
$response .= "<li> {$error}</li>";
}
$response .= "</ul></div>";
return response()->json([
'message' => $response
], 201);
}
// no errors
//continue with your logic
}
// javascript (jQuery)
$.ajax({
url: 'your_backend_url',
type: 'POST/PUT',
data: request_data, // maybe $(this).serializeArray()
beforeSend: () => {
// any stuff that you would like to do before sending the request,maybe showing a loader
},
success: (response, responseText, xhr) => {
if(xhr.status === 201)
{
// put errors in some element above or below the form
return $(".errors").html(response.message)
}
// clear previous errors
$(".errors").html("");
// success stuff here
}
});
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
$validator = Validator::make($request->all(), [
'barCodeNo' => 'required',
'propertyNo' => 'required',
]);
if ($validator->fails()) {
$response['code'] = 400;
$response['errors'] = $validator->errors()->toArray();
return response()->json(['response' => $response],400);
}