Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax calls return 419 error despite correct token in Laravel

Tags:

php

laravel

I have a bunch of POST requests made with Ajax in my Laravel application.

A typical request looks like:

$.ajax({
    url: '/path/to/method',
    data: {'id': id},
    type: 'POST',
    datatype: 'JSON',
    success: function (response) {
        //handle data
    },
    error: function (response) {
        //handle error
    }
});

I have the CSRF token set and everything works fine most of the time:

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

However, after a long hiatus (for example, computer asleep for a long time), all Ajax calls return a 419 error, as if the token wasn't set. After I reload the page everything is back to normal. This is on a local server.

How do I resolve this? Is there some way to "renew" the token before a call? Do I have to do the $.ajaxSetup bit before each call? It's not enough to do it once on page load?

like image 973
sveti petar Avatar asked Mar 22 '18 11:03

sveti petar


1 Answers

This is my suggestion:

JS

   //create a function to set header
    function setHeader(data){
        $.ajaxSetup({
            headers: {
               'X-CSRF-TOKEN': data
             }
         });
    }
   //in first load of the page set the header
    setHeader($('meta[name="csrf-token"]').attr('content'));

   //create function to do the ajax request cos we need to recall it when token is expire
    function runAjax(data){
      $.ajax({
         url: '/path/to/method',
         data: {'id': id},
         type: 'POST',
         datatype: 'JSON',
         success: function (response) {
            //handle data
         },
         error: function (jqXHR, textStatus, errorThrown) {
             if(jqXHR.status==419){//if you get 419 error which meantoken expired
                refreshToken(function(){refresh the token
                    runAjax();//send ajax again
                });
             }
         }
     });
    }

   //token refresh function
    function refreshToken(callback){
          $.get('refresh-csrf').done(function(data){
             setHeader(data);
              callback(true);
           });
    }
    //Optional: keep token updated every hour
     setInterval(function(){
            refreshToken(function(){
                    console.log("Token refreshed!");
                });

            }, 3600000); // 1 hour 

Route

//route to get the token
Route::get('refresh-csrf', function(){
    return csrf_token();
});

Hope this helps.

like image 188
Supun Praneeth Avatar answered Oct 29 '22 09:10

Supun Praneeth