422 Unprocessable Entity error after AJAX POST request in Laravel

13,158

From the validation, it seems that you are expecting reply-41 as the input field.

"reply-{$statusId}" => 'required|max:1000|alpha_dash',

But, from the ajax request you are making, it seems that you are passing the data in replyValue

data: {replyValue: $replyValue, _token:$token},

Thus, the validation rule is failing, because reply-41 is required.

You can update the server side to expect replyValue instead of reply-{$statusId} to solve it:

"replyValue" => 'required|max:1000|alpha_dash',
// ...
'body' => $request->input("replyValue"),
Share:
13,158
Felix
Author by

Felix

I build Laravel apps for fun

Updated on July 24, 2022

Comments

  • Felix
    Felix almost 2 years

    On my website, users can reply to blog posts.

    It's a bit annoying for the page to refresh when replying, so I decided to try ajax. However, I'm getting an error.

    Form/markup:

    <form data-value="{{$status->id}}" class="replyForm" role="form" action="{{ route('status.reply', ['statusId' => $status->id]) }}" method="post">
    <div class="form-group">
        <textarea name="reply-{{$status->id}}" class="form-control"  placeholder="Reply to this status"></textarea>
        @if ($errors->has("reply-{$status->id}"))
            <span class="help-block">
                {{ $errors->first("reply-{$status->id}") }}
            </span>
        @endif
    </div>
    <input type="submit" value="Reply">
    <input type="hidden" name="_token" value="{{ Session::token() }}" >
    </form>
    

    Controller:

    public function postReply(Request $request, $statusId) {
    
        $this->validate($request, [
            "reply-{$statusId}" => 'required|max:1000|alpha_dash',
          ], [
            'required' => 'The reply body is required.'
        ]);
    
        $status = Status::notReply()->find($statusId);
    
        if (!$status) {
            return redirect()->route('home');
        }
    
        if (!Auth::user()->isFollowing($status->user) && Auth::user()->id !== $status->user->id){
            return redirect()->route('home');
        }
    
        $reply = Status::create([
            'body' => $request->input("reply-{$statusId}"),
        ])->user()->associate(Auth::user());
    
        $status->replies()->save($reply);
        return redirect()->back();
    }
    

    Route:

    Route::post('/status/{statusId}/reply', [
        'uses' => '\CommendMe\Http\Controllers\StatusController@postReply',
        'as' => 'status.reply', 
        'middleware' => ['auth'],
    ]);
    

    Now this all works just fine. However, when I try to convert it into an Ajax request:

    $( ".replyForm" ).submit(function( e ) {
    
    e.preventDefault();
    
    var $token = $('input[name=_token]').val();
    var dataString = $(this).serialize();
    var $replyValue = $(this).attr('data-value');
    
    $.ajax({
        type: "POST",
        url: host + '/status/' + $replyValue + '/reply',
        data: {replyValue: $replyValue, _token:$token},
        success: function(res) {
    
        }
     });
    }); 
    

    I get the following error:

    POST XHR http://localhost/status/41/reply [HTTP/1.1 422 Unprocessable Entity 184ms]

    41 being the ID of the status being replied to.

    What's causing this?