detinu20
detinu20

Reputation: 319

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');
                        }
                    });
        });

Upvotes: 0

Views: 59

Answers (1)

Bak87
Bak87

Reputation: 219

When using ajax in laravel, and using POST method you always need to provide the csrf token, so what you need to do is:

In your HTML:

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

Before call Ajax:

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

Upvotes: 1

Related Questions