You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6使用Ajax登录返回422 Unprocessable Entity问题求助

Hey there! Let's dig into why your Laravel 5.6 Ajax login is throwing that 422 Unprocessable Entity error even with correct credentials and CSRF token configured.

First off, 422 errors in Laravel almost always point to validation failures—even if you think your credentials are correct, there’s likely a missing or misnamed field triggering the issue. Here’s how to diagnose and fix it step by step:

1. First, Check the Exact Validation Errors

The 422 response actually includes details about which fields failed validation, but you’re not seeing them yet. Add an error callback to your Ajax code to print these errors to the console:

$(document).ready(function () {
    $('#sign-in-form').submit(function(ev) {
        ev.preventDefault();
        formData = $('#sign-in-form').serialize();

        $.ajax({
            url: '{{route('login')}}',
            type: 'POST',
            data: formData,
            dataType: 'JSON',
            beforeSend: function () {
                // element.value='Processing...';
            },
            success: function(response) {
                // Your success logic here
            },
            error: function(xhr) {
                // This will show you exactly which fields failed validation
                console.log('Validation Errors:', xhr.responseJSON.errors);
            }
        });
    });
});

Open your browser’s dev tools (F12) and check the Console tab after submitting the form—this will tell you if, for example, your email field is missing, or your password doesn’t meet length requirements.

2. Verify Your Form Field Names Match Laravel’s Default Rules

Laravel’s default login validation expects fields named email and password. Double-check your form inputs to make sure their name attributes match exactly:

<form id="sign-in-form">
    @csrf <!-- Make sure this hidden CSRF field exists -->
    <input type="email" name="email" placeholder="Your Email">
    <input type="password" name="password" placeholder="Your Password">
    <!-- Optional remember me checkbox -->
    <input type="checkbox" name="remember"> Remember Me
    <button type="submit">Sign In</button>
</form>

If your inputs have names like user_email or pass, Laravel won’t recognize them, triggering a validation failure.

3. Confirm CSRF Token is Actually Being Sent

Even if you think you’ve set it up, double-check:

  • Either include the @csrf directive in your form (as shown above)—serialize() will automatically include this hidden field.
  • Or, if you prefer setting it via headers, add this to your script before the submit handler:
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    And make sure your layout has the meta tag:
    <meta name="csrf-token" content="{{ csrf_token() }}">
    

4. Check Your Login Route’s Method

Run php artisan route:list in your terminal to confirm the login route uses the POST method. Laravel’s default login route does, but if you’ve customized it, a mismatched method (like GET) could cause issues.

5. Handle the "Remember Me" Field (If Used)

If you have a remember me checkbox, note that serialize() won’t include it if it’s unchecked. Laravel’s default validation marks remember as optional, so this shouldn’t cause a 422—but if you’ve added a custom rule requiring it, that could be the culprit.

Example Fixed Ajax Code

Here’s a polished version of your script with error handling and best practices:

$(document).ready(function () {
    // Set up CSRF header globally
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('#sign-in-form').submit(function(ev) {
        ev.preventDefault();
        const formData = $(this).serialize();
        const submitBtn = $(this).find('button[type="submit"]');

        // Disable button during request
        submitBtn.val('Processing...').prop('disabled', true);

        $.ajax({
            url: '{{ route('login') }}',
            type: 'POST',
            data: formData,
            dataType: 'JSON',
            success: function(response) {
                // Redirect on success
                window.location.href = '/dashboard'; // Replace with your dashboard route
            },
            error: function(xhr) {
                // Reset button state
                submitBtn.val('Sign In').prop('disabled', false);
                
                // Show errors on the page (optional)
                $.each(xhr.responseJSON.errors, function(field, messages) {
                    $(`#${field}-error`).text(messages[0]);
                });
            }
        });
    });
});

Start with checking the validation errors via the console—that’s the fastest way to pinpoint the exact issue. Once you know which field is failing, fixing it should be straightforward!

内容的提问来源于stack exchange,提问作者Saimikram84

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:48:35