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

birendragurung's avatar

HTTP Response code for TokenMismatchException in ajax requests

I'm sending my requests to the server using ajax and somehow at times, I may get TokenMismatchException on the server. Now, I want to handle this both on the backend as well as frontend. For this, I think I need to do this:

    public function render($request , Exception $exception)
    {
        //TODO Check the following if() block code validity for production server
        if ($exception instanceof \Illuminate\Session\TokenMismatchException){
            if ($request->expectsJson() ){
                return Response::json([
                    'message'      => 'Token mismatch (CSRF token mismatched)' ,
                    'message-type' => 'danger' ,
                    'new_csrf_token' => csrf_token()
                ], $exception->getStatusCode());
            }
            return redirect()
                ->back()
                ->exceptInput('password')
                ->with([
                    'message'      => 'Validation Token was expired. Please try again' ,
                    'message-type' => 'danger' ,
                ]);
        }

        return parent::render($request , $exception);
    }

Using this JSON response, I want to display a prompt message on the front end as well as update the CSRF token to resend the request.

0 likes
1 reply
mballaag's avatar

on your code. can you have this ;

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

and this

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

Please or to participate in this conversation.