How to display validation errors of AJAX requests?
AJAX Requests & Validation
In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
error: function (response) {
if (response.status ==422){
displayFieldErrors(response);
}else{
/**
* Uses Notify.js to display validation errors
* next to the relevant field
* @param response
*/
function displayFieldErrors(response){
var gotErrors = false;
var errorPostion = "top";
$.each(response.responseJSON, function (key, item) {
//key is the field
$gotErrors = true;
$("#" + key).notify(item, {position: errorPostion});
if (errorPostion === "top") {
errorPostion = "bottom";
} else {
errorPostion = "top";
}
});
return gotErrors;
@curtisblackwell thank you for your response. I also wonder if is it possible to set a global handler for any axios request. For example I want to listen every ajax requests globally and if any of them returns with an "not authenticated" error, I want to redirect user to login page...
@mottoskorzeny I've not done so myself, but it sounds like interceptors would make that simple to implement. You might want to set the interceptor(s) on a customized instance of axios.
…oh wow. Just saw how long ago this is from. Only now noticed a notification.