Matt Pierce
Matt Pierce

Reputation: 805

Laravel AJAX 500 Internal Server Error, Tokens Match

When I submit the form, I get this error and the page automatically reloads, but the url in the browser then shows my route and content that I posted in the form. Then, if I go ahead and submit again without reloading the page it works just fine. Could it be that I'm not posting the token itself? I have added the meta tag to the head.

<meta name="csrf-token" content="{{ csrf_token() }}" />

JS:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('#postForm').submit(function(){

    var body = $('#postbody').val();
    var profileId = $('#user_id').text();

        $.ajax({
            type: "POST",
            url: "/post/"+profileId,
            data: {post:body, profile_id:profileId},
            success: function(data) {
                console.log(data);
            }
        });
});

Route:

Route::post('/post/{id}', [
    'uses' => '\App\Http\Controllers\PostController@postMessage',
    'as' => 'post.message',
    'middleware' => ['auth'],
]);

Controller:

public function postMessage(Request $request, $id)
{
    if(Request::ajax())
    {
        $this->validate($request, [
            'post' => 'required|max:1000',
        ]);

            $newMessage = Auth::user()->posts()->create([
                'body' => $request->input('post'),
                'profile_id' => $id
            ]);
    }
}

View:

<form role="form" action="#" id="postForm">
    <div class="feed-post form-group">
        <textarea class="form-control feed-post-input" id="postbody" name="post"></textarea>
        <div class="btn-bar">
            <button type="submit" class="btn btn-default btn-post"></button>
        </div>
    </div>
    <input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</form>

UPDATE:

So, the log says that "Request::ajax() should not be called statically" in my controller. I removed that code and it works fine now. However, I want to know if removing it is ok to do of if there's a better way to resolve this. Thanks!

ANSWER: It works by changing

if (Request::ajax()){
    // code...
}

to

if ($request->ajax()){
    // code...
}

Upvotes: 0

Views: 158

Answers (2)

oseintow
oseintow

Reputation: 7421

Change Request::ajax() to $request->ajax()

Upvotes: 1

Denis Mysenko
Denis Mysenko

Reputation: 6534

You are doing an AJAX post – you are not supposed to be redirected anywhere at all. If there is an error – you should only see it in Developers Tools in your browser.

Try adding:

$('#postForm').submit(function(e) {
    e.preventDefault();
    ...
}

So that browser doesn't post the form instead of your AJAX call. Also try fixing your header case: X-CSRF-TOKEN to X-CSRF-Token

Also, your postMessage() method doesn't return anything at all. You should probably notify the user of the result there or just return $newMessage.

Upvotes: 0

Related Questions