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

dionarap's avatar

500 Internal error - error TokenMismatchException

Seem to be having problems with a TokenMismatchException on my Javascript button that are approving a comment. I have copied the code from a similar button system and changed it to match the requirements of this system. I am reusing the Session:Token variable, not sure if thats the issue?

Error: TokenMismatchException in verifycsrftoken.php line 68

Here is my code, any ideas on why i'm getting the mismatch error?

HTML:

@if(Auth::user())
       @if($approval)
         <a class="approval approved " data-id="{{$comments->id}}"><i class="fa fa-thumbs-up"></i></a>
        @else
        <a class="approval not-approved " data-id="{{$comments->id}}"><i class="fa fa-thumbs-up"></i></a>
        @endif

        @else
        <a class="not-approved" href="{{route('login')}}"><i class="fa fa-thumbs-up"></i></a>
        @endif

Javascript:

        var token = '{{ Session::token() }}';
        var urlApproval = '{{ route('approvals') }}';
        $('.approval').on('click', function(event){
            event.preventDefault();
            var buttonToChange = $(this);
            var $this = $(this);

            $.ajax({
                        method: 'POST',
                        url: urlApproval,
                        data: { comment_id: $(event.target).data("id")}, _token: token })

                    .done(function() {
                        if(buttonToChange.hasClass('approved')) {
                            buttonToChange.addClass('not-approved');
                            buttonToChange.removeClass('approved');
                        }else {
                            buttonToChange.addClass('approved');
                            buttonToChange.removeClass('not-approved');
                        }
                    });
        });
0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

Don't read the token from session. It changes. Also, I think that's the session token and not the csrf token. It's better to set it in the <head> of your document, and then read it.

See how they do it in the docs, and then you don't have to manually set it for each request. Just set it in ajaxSetup().

https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token

jlrdw's avatar

There are pages and pages of previous answers on how to properly do this stuff. One long post was a couple of weeks ago, very detailed.

Please or to participate in this conversation.