I am doing an ajax request with jquery and I want to send one data to the server (the id of the clicked button) so I can make the correct query and return the correct reponse. The idea is that after I click a button I should make the ajax call to request a datatable. My jquery function looks like this:
$('button').click(function(){
var dep_id = $(this).attr('id');
var table = $('#dataTable').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url" : '{!! route('workerDepData') !!}' ,
"type" : "POST" ,
"data" : { id: dep_id }
},
columns: [
{ data: 'id', name: 'id' },
{ data: 'worker_name' , name:'name' },
{ data: 'role', name: 'role' },
{ data: 'dep_name' , name:'dep_id'} ,
{ data: 'created_at', name: 'created_at' } ,
{
"className": "details",
"orderable": false,
"data": null,
"defaultContent": '<button class="btn btn-success" id="show">Show</button>' }
]
} );
My route is like below:
Route::post('/dep/fetch/workers' , 'DepsController@fetch_workers')->name('workerDepData');
My fetch_workers function inside the controller has this code:
public function fetch_workers()
{
$workers = DB::table('workers')
->where('workers.dep_id' , '=' ,request('id'))
->join('departaments' , 'workers.dep_id' , '=' , 'departaments.id')
->select('workers.id' , 'workers.name as worker_name' , 'workers.role' , 'departaments.name as dep_name' , 'workers.created_at')
->get();
$ajaxResponse = Datatables::of($workers)->make(true);
return $ajaxResponse;
}
After I click the button I get an error and when I check the response from the server due to the ajax request , I see a json file which have an exception at
Symfony\Component\HttpKernel\Exception\HttpException.
I check for this kind of exception and I saw it was due to a route using get instead of post. My route as you can see is using post so I don't understand why is this exception.
As I have mentioned in comments. Its CSRF token issue.
In order to fix it
1) You can exclude your URI for CSRF
2) You can put csrf_token() to your ajax request.
Detailed explaination can be found here https://laravel.com/docs/5.5/csrf
You must include CSRF token in both blade form and post method.
var _token = $("input[name='_token']").val();
and pass together with other data.
data: { _token:_token , etc:etc },
have fun :)
Laravel: For those who are facing with csrf issue with ajax in laravel
<?php
if(condition){
$updated_field = 'User' ;
$id = $t->updated_value;
echo '<script type="text/javascript">';
echo '$(document).ready(function(){
var updated_value ='. $id .';
//alert(updated_value);
$.ajaxSetup({
headers : { "X-CSRF-TOKEN" :jQuery(`meta[name="csrf-token"]`). attr("content")}
});
$.ajax({
type:"POST",
url : "get_username",
data : { id: id },
success: function(){
console.log(data);
}
});
});';
echo '</script>';
}
?>
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