Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sunrise's avatar

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.

This is the content about “AJAX Requests & Validation” in the documentation.
https://laravel.com/docs/5.2/validation#quick-ajax-requests-and-validation
The question is:
How to display validation errors of AJAX requests?

0 likes
7 replies
tykus's avatar

Like it says, you get an error (422) response with a JSON payload having the validation errors

If you're using jQuery:

   $.ajax(url, {
      success: function(data) {
         // handle the successful response
      },
      error: function(xhr, status, error) {
    // handle the error
     }
   });
2 likes
phpMick's avatar

I do it like this currently (using notify.js):

 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;

1 like
curtisblackwell's avatar

@mottoskorzeny Try this to see some options:

axios
  .post(form.action, data)
  ...
  .catch((failure) => {
    console.dir(failure);
  });

You'll see you get access to the validation errors in failure.response.data.

2 likes
mottoskorzeny's avatar

@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...

nicknds97's avatar

Thanks, was hunting down this solution for few days now.

Please or to participate in this conversation.