Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Laravel validation errors do not arrive as JSON in an AJAX call

ErrorThe AJAX call returns the whole login or form page as HTML after a failed validation

Short answer

For XHR requests Laravel's validate() returns a 422 response with a JSON body that holds an errors object. If you get a redirect or an HTML page instead, Laravel did not see the call as one expecting JSON: send Accept: application/json. If the call succeeds but you see nothing, you are reading the error in the success callback.

  • Applies to Laravel 12, PHP 8.3, jQuery 3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Open the request in the browser's network tab or replay it with curl and the Accept header. The status code and the first bytes of the body tell the causes apart.

    curl -i -X POST http://localhost:8000/api/orders \
      -H "Accept: application/json" \
      -d "qty=abc"
  2. 2Match what you see, then jump to its fix

    1. 1Status 302 with a Location header, or a 200 with an HTML page, for a request that failed validationThe request does not say it expects JSONFix
    2. 2The network tab shows 422 with the right JSON, but the page shows no messagesThe 422 goes to the error callback, not the success oneFix
    3. 3The errors object has keys like users.0.email, and your code looks for users[0][email]Nested field names are flattened in the error keysFix

What does the error look like?

  • The AJAX call returns the whole login or form page as HTML after a failed validation
  • The browser shows a 302 redirect for a failed validation on an API route
  • 422 Unprocessable Entity with a JSON body: message and errors

Cause 1 of 3

The request does not say it expects JSON

1Check

Laravel returns the JSON error format when the request is XHR or expects JSON. Laravel reads this from the Accept header, through the expectsJson() check on the request.

curl -i -X POST http://localhost:8000/api/orders -d "qty=abc" | head -n 5

2Fix

Send the Accept header from the client. With plain fetch, set it yourself. jQuery's $.ajax already adds X-Requested-With: XMLHttpRequest by default.

fetch('/api/orders', {
  method: 'POST',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  body: JSON.stringify({ qty: 'abc' }),
});

3Verify

The same curl call, with the Accept header, answers 422 and a JSON body.

curl -i -X POST http://localhost:8000/api/orders -H "Accept: application/json" -d "qty=abc" | head -n 12

Confirmed by laravel.com

Did this fix it?

Cause 2 of 3

The 422 goes to the error callback, not the success one

1Check

jQuery calls the error callback for HTTP status errors, and with dataType json it exposes the parsed body as jqXHR.responseJSON. Laravel puts the messages under errors, keyed by field name.

grep -rn "\$.ajax\|\$.post" resources/js public/js 2>/dev/null | head

2Fix

Read the errors in the error handler and loop over the keys.

$.ajax({
  url: '/api/orders', method: 'POST', dataType: 'json', data: { qty: 'abc' },
  error: function (jqXHR) {
    if (jqXHR.status === 422) {
      const errors = jqXHR.responseJSON.errors;   // { qty: ["..."] }
      Object.keys(errors).forEach(k => console.log(k, errors[k][0]));
    }
  }
});

3Verify

Submit invalid data: the messages appear next to the fields.

curl -s -X POST http://localhost:8000/api/orders -H "Accept: application/json" -d "qty=abc"

Confirmed by api.jquery.com

Did this fix it?

Cause 3 of 3

Nested field names are flattened in the error keys

1Check

Laravel documents that nested error keys are flattened into dot notation.

curl -s -X POST http://localhost:8000/api/users -H "Accept: application/json" -d "users[0][email]=x"

2Fix

Map the dot-notation key to your input, for example by converting the dots to the bracket syntax of your form.

const key = field.replace(/\.(\w+)/g, '[$1]');   // users.0.email -> users[0][email]

3Verify

The message shows next to the right input.

curl -s -X POST http://localhost:8000/api/users -H "Accept: application/json" -d "users[0][email]=x"

Confirmed by laravel.com

Did this fix it?

How do I stop it coming back?

  • Make every API client send Accept: application/json, and put it in your shared HTTP wrapper.
  • Handle 422 in one place in your front-end code, and show the errors from that single handler.
  • Write a feature test that posts invalid data with getJson/postJson and asserts the 422 and the error keys.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

composer require maatwebsite/excel fails to install

Composer says the package needs an older PHP than the one installed

Composer refuses maatwebsite/excel when the PHP version or a PHP extension does not match what the package and PhpSpreadsheet need.

3 causes, each with a fix

Back end

composer require laravel/horizon fails: ext-pcntl is missing

laravel/horizon v1.1.0 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system

Horizon needs the pcntl extension, and Composer refuses to install it where PHP lacks that extension.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.