Search code examples
jqueryajaxlaravellaravel-5csrf

How to to handle token mismatch exception in laravel post ajax?


In my Laravel 5.4, I use the following code in my ajax using jQuery:

            $.ajax({
                url     : 'http://example.com/addmember',
                method    : 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend  : function()
                {},
                data : $('#theForm').serialize(),
                success   : function(response)
                {
                   // I do something here
                },
                error : function(e)
                {
                    console.log(e);
                },
                complete : function(c){
                }
            });

I sometimes get a token mismatch exception like so: enter image description here I generally get this error when the user stays on the page for a very long time before firing the AJAX request.

How can i handle the situation ?

I even made a middleware that upon a token mismatch on an ajax call returns a response like response.status == "TOKEN-ERROR" on getting this i reload the page using window.loaction.reload(1);.

Is there any more efficient method to handle the situation without reloading the page and thus loosing the user's progress ?


Solution

  • In your app/Exceptions/Handler.php file

    Add a handler for TokenMismatchException in the render method

    public function render($request, Exception $exception)
    {
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            if ($request->expectsJson()) {
                return response()->json([
                    'error' => 'Token mismatch'
                ], $exception->getStatusCode());
            };
        }
    
        return parent::render($request, $exception);
    }
    

    This will return an error json response. You can customize the error response to suit your needs.