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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With