Reputation: 733
I am trying to do a post with ajax to laravel. When using the get method it works fine but with the POST, it fails.
Here is the code: on my app.blade, I have put:
<meta name="csrf-token" content="{{ csrf_token() }}" />
on my view.blade, I have the following ajax code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#employeeActivityTable').DataTable( {
ajax: {
url: "{!! route('ajaxactivityperemployee') !!}",
type: "POST"
},
columns: [
{ data: 'employee_id', name: 'employee_id' },
{ data: 'employee_name', name: 'employee_name' },
{ data: 'month', name: 'month' },
{ data: 'sum_task_hour', name: 'sum_task_hour' }
],
columnDefs: [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
}
]
} );
...
I know that my routes are working because I had everything with GET and it worked fine and I only changed it to POST and I get in the troubleshooter tool:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
And here are my routes:
//Employee activity
Route::get('employeeactivity', ['uses'=>'EmployeeActivityController@getView','as'=>'employeeactivity']);
//AJAX
//Activity per employee
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
Route::get('activityperproject', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerProject','as'=>'ajaxactivityperproject']);
Route::post('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@postActivityPerEmployee']);
and here is the ajax controller:
public function getActivityPerEmployee()
{
$return = $this->activityRepository->getActivityPerEmployee();
$data = Datatables::of($return)->make(true);
return $data;
}
public function postActivityPerEmployee(Request $request)
{
$where = [['col'=>'employee_id','val'=>'13'],['col'=>'month','val'=>'Jan']];
$return = $this->activityRepository->getActivityPerEmployee($where);
$data = Datatables::of($return)->make(true);
return $data;
}
public function getActivityPerProject()
{
$return = $this->activityRepository->getActivityPerProject();
$data = Datatables::of($return)->make(true);
return $data;
}
Again, if in the ajax request, I change the type from POST to GET, everything works fine.
Upvotes: 1
Views: 266
Reputation: 1951
You are trying to send a Post request to a Get Route.
{!! route('ajaxactivityperemployee') !!}"
Related Route is :
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
So in your case you can do somehting like this (give a name to your post route) :
Route::post('activityperemployee','uses'=>'Ajax\ActivityAjaxController@postActivityPerEmployee', 'as'=>'postajaxactivityperemployee']);
and then use your new named route in your ajax call :
{!! route('postajaxactivityperemployee') !!}"
which will call postActivityPerEmployee
action
Upvotes: 2