laravel-datatables: 401 Unauthorized
I updated today to 5.11.7 version and I am having some randomly unauthorized error from the ajax when I enter to the page where I have Datatables component. My code is like this
public function anyData()
{
$Patient = Patient::select('*')->withTrashed();
return \Datatables::of($Patient)->make(true);
}
and the datatable declaration is
$(document).ready(function() {
$('#dataTables-patients').DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: base_url+'/patient/data',
language:{
url:base_url+'/js/dataTables.Spanish.json'
},
columns:[
{data:'dni', name:'dni'},
{data:'first_name', name:'first_name'},
{data:'last_name', name:'last_name'},
{data:'birthday', name:'birthday'},
{data:'id', name:'id'},
{data:'active', name:'active'},
],
"columnDefs": [{
"targets": 4,
"data": "id",
"render": function ( data, type, row ) {
if(row.active=="0"){
return '<a class="btn btn-primary" href="'+base_url+'/patient/show/'+data+'">'+patient.view+'</a>'+
'<a class="btn btn-success respatient" data-id="'+data+'" href="#" >'+patient.restore+'</a>';
}else{
return '<a class="btn btn-primary" href="'+base_url+'/patient/show/'+data+'">'+patient.view+'</a>'+
'<a class="btn btn-danger delpatient" data-id="'+data+'" href="#" >'+patient.delete+'</a>';
}
}
},
{ "orderable": false, "targets": [ 4 ] },
{ "bSearchable": false, "aTargets": [ 5 ] },
{ "visible": false, "targets": [ 5 ] }
]
});
});
when Unauthorized explodes, I have to re login on the app. and it happens randomly: I can reload 6 times the page and happens nothing, and sometimes I enter two times and unauthorized happens.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 4
- Comments: 16 (5 by maintainers)
Reading the comments, I solved the problem well. in the view
var token = '{{ csrf_token() }}';
ajax: { url:'$url', type:'post', data: { '_token': token } },
`var table = $(‘#myTable’);
, { "iDataSort": 1, "aTargets": [ 0 ] },
`
I solved this little problem as follows replaces: ajax: ‘resource’,
by: ajax: { url: ‘resource’, headers: {‘X-CSRF-TOKEN’: token}, dataType: ‘JSON’, beforeSend: function (xhr) { xhr.setRequestHeader(‘Authorization’); } },
Some tips
Hello, I’ve encountered this issue and tried to debug for hours but to no avail. It seems that one workaround is to set your ajax as a POST request instead of GET This worked for me and i tested by refreshing my page 50 times without getting kicked out to the login page
The workaround is based on this issue https://github.com/yajra/laravel-datatables/issues/19
I’m using apache on a Fedora machine, using locally via the hosts file and i’m having this exact same issue. Any ideas?