I am facing an issues bring Datatables into my existing laravel application.
I have follow a couple of videos and getting stuck.
I have the following in my MembersController.php file
namespace App\Http\Controllers;
use Alert;
use DataTables;
use App\Member;
class MembersController extends Controller
{
public function index()
{
//
return view('members.index');
//, compact('members'));
}
function getdata()
{
$members = Member::where('active', '!=', 'N')->where('member_type',
'=', 'League')->get();
return Datatables::of($members)->make(true);
}
I have the following in my Route/web.php
Auth::routes();
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/members', 'MembersController')->middleware('auth');
// Ajax requests
Route::get('members/getdata', 'MembersController#getdata')->name('members.getdata');
I have the following Script in my members/index.blade
<script>
// Write on keyup event of keyword input element
$(document).ready(function(){
$('#table').Datatable({
"processing": true,
"serverSide": true,
"ajax": "{{ rount('members.getdata')}}",
"columns" :[
{"data": "first_name"},
{"data": "last_name"},
{"data": "memberrank->rank"},
{"data": "ActiveKids->sum('balance')"}
]
});
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($("#roll tbody tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) ===
-1)
{
$(this).hide();
}
else
{
$(this).show();
}
});
});
});
</script>
However I get the following error:
"Call to underined function rount()
This points the issue to the javascript
"ajax": "{{ rount('members.getdata')}}",
"ajax": "{{ route('members.getdata')}}",
Related
I'm trying to use the id from my show function in my controller,
My controller works correctly with this $id
public function show($id)
{
$DigestReport = Meo::find($id);
return view('digest-report.show', ['DigestReport' => $DigestReport]);
}
I'm trying to use the same $id for another function
public function getMailRecipients($id){
$meoId = Meo::find(id);
$mailRecipients = $this->meoRepository->getMailRecipients($meoId);
return DataTables::of($mailRecipients)->make();
}
but I get the following error
Too few arguments to function
DigestReportController::getMailRecipients(), 0 passed on line 54 and
exactly 1 expected
How can I fix it?
added: if necessary, this is my repository
public function getMailRecipients($meoId){
return DB::table('mail_recipients')->where('meo_id', '=', $meoId)->select('id', 'name', 'email')->get();
My api.php where are my stored routes
Route::get('/digest-report/mail-recipients', 'DigestReportController#getMailRecipients')->name('digest-report.mail-recipients');
My view where I'm using this controller, is for make a datatable
$(document).ready(function () {
$('#mail-recipient-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": '{{route('digest-report.mail-recipients')}}',
"columns": [{data:'id'},{data: 'name'},{data: 'email'}]
});
})
Thanks
Ok you have two ways to do this
in your web.php you will update your route to be
Route::get('/digest-report/mail-recipients/{id}', 'DigestReportController#getMailRecipients')->name('digest-report.mail-recipients');
then you javascript code will be
$(document).ready(function () {
$('#mail-recipient-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": '{{route('digest-report.mail-recipients', $DigestReport->id)}}',
"columns": [{data:'id'},{data: 'name'},{data: 'email'}]
});
})
in you controller you will update getMailRecipients
public function getMailRecipients(Request $request){
$meoId = Meo::find($request->id); // or using helper request('id') function
$mailRecipients = $this->meoRepository->getMailRecipients($meoId);
return DataTables::of($mailRecipients)->make();
}
and your javascript code will be the same
I used GET method first and I would get this error:
414 (Request-URI Too Long)
My ajax is like this:
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'GET',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my route:
Route::get('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
But then i get error: 414 (Request-URI Too Long)
If i switch to POST type adn switch my route to post i will get this error:405 (Method Not Allowed)
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'POST',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my POST route:
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
My controller
public function tabela_evidencije(Request $request, $id, $tip)
{
$evidencija = EvidencijaRadnikaPoDanu::with('radnik', 'radnik.identifikacija')
->select('evidencija_radnika_po_danus.*', 'radniks.id_identifikacije')
->where('evidencija_radnika_po_danus.id_kompanije', Auth::user()->id_kompanije)
->where('evidencija_radnika_po_danus.id_radnih_dana', $id)
->where('evidencija_radnika_po_danus.tip', $tip);
return datatables()->of($evidencija)
->editColumn('id_radnika', function ($data) {
$puno_ime = $data->radnik->prezime.' '.$data->radnik->ime;
return $puno_ime;
})
->editColumn('id_ime', function ($data) {
return $data->radnik->ime;
})
//pomocu veze izmedju radnika i evidencija pronalazimo identifikacioni broj
->editColumn('id', function ($data) {
return $data->radnik->identifikacija->broj;
})
->editColumn('id_radnika_modal', function ($data) {
return $data->id_radnika;
})
->editColumn('id_modal', function ($data) {
return $data->id;
})
->make(true);
}
After inspecting it while using GET my URL is over 8,000 characters!
I added in my <head> this:
<meta name="csrf-token" content="{{ csrf_token() }}">
and added token in my ajax POST method
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
method: 'POST',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}...
And also changed my route to be post
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
And i had to run this command in my console
php artisan optimize
In order for my route to change to POST route...
Currently, i am on the show page that is i am running the function show as in my controller so my url is showing like dashboard/1/people in the url address bar. Now, when i click on a person, it routes to a different page and that is where getPeople is called.
How can i get the id of the person i clicked which is 1 from the ajax request in the scripts and pass to my controller?
PS: At the moment, i have hardcoded 1 in the ajax request but i want it to be dynamic please
How do i get this done?
Script
datatable = $('#table').DataTable({
"ajax": "{{ route('dashboard/1/people') }}",
"columns": [
{data: 'check', name: 'check'},
],
Controller
public function show($id)
{
$class = Class::whereId($id)->first();
return view('show');
}
public function getPeople($id)
{
$get_id = $id;
$class = Class::whereId($get_id)->first();
$people = $class->peoples()->get();
return Datatables::of($people)->addColumn('action', function ($ppl) {
//return
})->make(true);
}
This should work:
In your getPeople method store the id in a session variable:
public function getPeople($id)
{
$get_id = $id;
//using session helper method
session(['show_id' => $id]);
$class = Class::whereId($get_id)->first();
$people = $class->peoples()->get();
return Datatables::of($people)->addColumn('action', function ($ppl) {
//return
})->make(true);
}
and then access it in you ajax code:
datatable = $('#table').DataTable({
"ajax": "{{ route('dashboard/'.session('show_id').'/people') }}",
"columns": [
{data: 'check', name: 'check'},
],
DataTable ajax allows yo to pass extra parameters in object format just like this:
datatable = $('#table').DataTable({
"ajax": {
"type": "GET",
data:{id: my_id_var},
"url": "my_route"
}
}
And in your function just get the Request var
public function getPeople(Request $request){
$get_id = $request->id;
$class = Class::whereId($get_id)->first();
$people = $class->peoples()->get();
return Datatables::of($people)->addColumn('action', function ($ppl) {
//return
})->make(true);
}
More Information in Sorce Page
this is JS code:
<script type="text/javascript">
$(document).ready(function(){
$('#add-more-acadimic').on('click', function(){
$('#add-new-acadimic').modal();
});
$('#SaveAcadimic').on('click', function(){
var name = $('#acadimic').val();
$.post("{{ route('postInsertAcadimic')}}",{name: name},function(data){
console.log(data);
});
});
});
</script>
and this is my route file
Route::post('/manage/course/insert_acadimics', [
'uses' => 'CourseController#postInsertAcadimic',
'as' => 'postInsertAcadimic'
]);
this is controller function
public function postInsertAcadimic(Request $request)
{
if($request->ajax())
{
return response(Academic::create($request->all()));
}
}
and i use csrf token meta tag along with this code in master blade:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}});
and this is the console error:
POST http://localhost:8000/manage/course/insert_acadimics 500 (Internal Server Error) XHR failed loading: POST "http://localhost:8000/manage/course/insert_acadimics".
and this is laravel log error:
[2017-08-06 19:32:42] local.ERROR: exception 'Symfony\Component\Console\Exception\RuntimeException' with message 'Too many arguments, expected arguments "command" "name".' in C:\xampp\htdocs\SMS\vendor\symfony\console\Input\ArgvInput.php:181
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.
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