My laravel Yajra datatable does not render. It says invalid json response. However I can not read the error since the response is empty - laravel

Hello I have the following controller method to return data to my datatable in Laravel,
Controller Method
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->make(true);
}
Then in the view I render the datatable, I have the following code.
<table id="users-table" class="table table-condensed table-hover">
<thead>
<tr>
<th>Username</th>
<th>NIC</th>
<th>Mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
Inside my script tag I have the below code
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route("admin.app-access.user.get") }}',
type: 'get',
data: {status: 1, trashed: false}
},
columns: [
{data: 'email', name: 'email'},
{data: 'nic', name: 'nic'},
{data: 'mobile', name: 'mobile'},
{data: 'status', name: 'status'},
{data: 'actions', name: 'actions'}
],
pageLength:25,
lengthMenu:[[10,25,50,100,-1],[10,25,50,100,"All"]],
order: [ [ 0, "desc" ] ],
dom: "lBfrtip",
buttons:
[
{extend: 'excel', footer: true, title: 'User Details'},
{extend: 'pdf', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'},
{extend: 'print', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'}
],
searchDelay: 500
});
});
The Error
When I go to the index page that the datatable is loaded, it says,
DataTables warning: table id=users-table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What I tried
I tried making a little syntax error in the above controller method to see if the application crashes. If the application crashes, it means that the request sent from the datatable must have hit my controller method. (App actually crashed, so the request from the datatable is coming to my controller method.)
I went to the network tab in my developer tools and inspected the response for the request sent from the data-table. The response is empty. It just shows three empty lines. Since the response is empty, I can not figure out what the error is.
Below picture shows the response I got.
(I am using Laravel 5.4)

I have added rawColumns before the ->make(true) will you try with this solution once?
It should work I guess so!
So here your will looks like...
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->rawColumns(['status', 'actions'])
->make(true);
}

Related

Laravel: DataTables warning: table id=dataTable - Invalid JSON response

I try to fetch the data from the database and show it in the yajra datatable but I get this error
and I get this error in the inspect network (This request has no responce data avallible)
My Route:
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::resource('countries', CountryController::class);
Route::get('countries/indexTable', [CountryController::class, 'getAllCountries'])
->name('countries.datatables');
});
Controller:
public function index()
{
return view('countries.index');
}
public function getAllCountries(Request $request)
{
return Datatables::of(Country::query())->make(true);
}
View:
<table class="table table-bordered table-hover table-striped mb-4" id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>{{__('general.name')}}</th>
<th>{{__('general.code')}}</th>
</tr>
</thead>
</table>
script:
$(function() {
var url = window.location.href;
$('#dataTable').DataTable({
processing: true,
serverSide: true,
searching: true,
ajax:
{
url: url + '/indexTable',
},
columns:
[
{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'code',
name: 'code'
},
],
});
});

Can't get user_id value Laravel Query

I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance
I have a controller contain following code
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')->select('name')->selectraw('count(user_id) as total')->selectRaw('SUM(status = "Done") as done')->where('div', Auth::user()->div)->groupBy('name')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.teamTask',);
}
my view
<script type="text/javascript">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('team.task') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'name',
name: 'name',
orderable: false,
},
{
data: 'user_id',
name: 'user_id',
orderable: false,
},
{
data: 'total',
name: 'total',
orderable: false,
},
{
data: 'done',
name: 'done'
},
{
data: 'action',
name: 'action'
},
]
});
});
</script>
I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance
Add ->groupBy('user_id') in your query, this should fix your problem
Try this.
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')->select('name','user_id')->selectraw('count(user_id) as total')->selectRaw('SUM(status = "Done") as done')->where('div', Auth::user()->div)->groupBy('name')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.teamTask',);
}

Laravel Datatables - Invalid JSON response

I have the following which returns an Invalid JSON response while using Laravel Datatables.
Routes
Route::get('/products', 'ProductController#index')->name('products');
Route::get('/getproducts', 'ProductController#getProducts')->name('getProducts');'
Controller
public function index()
{
return view ('backend.products.home');
}
public function getProducts()
{
return Datatables::of(Product::query())->make(true);
}
View
<table id="myTable">
<thead>
<tr>
<th>Product</th>
<th>Manufacturer</th>
<th>Price</th>
</tr>
</thead>
</table>
Script
<script>
$(function() {
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('getProducts') !!}',
columns: [
{ data: 'product_name', name: 'product_name' },
{ data: 'manufacturer', name: 'manufacturer' },
{ data: 'price', name: 'price' },
]
});
});
</script>
When I return Datatables::of(Product::query())->make(true) in the products view, I am getting the JSON like so:
Try this:
return Datatables::of(Product::query()->select('*'))->make(true);
Or:
return Datatables::of(Product::query()->get())->make(true);

A non well formed numeric value encountered when creating a custom Yajra Datatable

I am using Laravel and I want to create a custom server side Yajra Datatable.
My Ajax call is below:
let table = $('#myTable').DataTable({
"bLengthChange": false,
"iDisplayLength": 20,
"info": false,
processing: true,
serverSide: true,
ajax: {
url: "/myURL",
dataSrc: '',
data: function (d) {
d.start = '2020-04-01';
d.end = '2020-07-20';
d.table = true;
},
},
columns: [
{data: 'name', name: 'name'},
{data: 'nameMerged', name: 'nameMerged'},
{data: 'count', name: 'count'},
],
});
$("#myTable").append('<tfoot><tr><th>' + 'Total:' + '</th><th></th><th>'
+ total + '</th></tr></tfoot>');
The controller for the ajax call is getting an array from another function that looks like (tableObject) and transforms the array into a Datatable.
DataTable transform function:
public function transformTable($start, $end)
{
$tableObject = $this->getTableData($start, $end);
return DataTables::of($tableObject['datasets'])
->addIndexColumn()
->addColumn('name', function ($row) {
return $row->name;
})
->addColumn('nameMerged', function ($row) {
return $row->nameMerged;
})
->addColumn('count', function ($row) {
return $row->count;
})
->setRowClass(function ($data) {
return 'tr-basic';
})
->with('total', $tableObject['total'])
->make(true);
}
Table in Blade file:
<div>
<h2>Employees:</h2>
<table id="myTable" class="bravo-list">
<thead>
<tr>
<th class="th-toggler"></th>
<th class="th-fullname" id="th-employee">Mitarbeiter</th>
<th class="th-fullname" id="th-count"># Bravos</th>
</tr>
</thead>
</table>
</div>
This, however, returns the following error:
A non well formed numeric value encountered
The error occurs beacause the variables "start" and "end" in the ajax call are reserved keywords. I changed the name of the variables and it works now as aspected.

Yarja Datatables - getting results for specific id

I am trying to have the ability for the user to click on a link and get jobs for a specific operative. As a test I am only using three field from a job table
id,operative_id,address
The operative ID is the parameter I wish to pass to the datatable ajax controller.
The operative ID is sent by the jobs controller to a blade template in the normal manner. I then have a table area:
<table class="table data-table" id="thetable">
<thead>
<th>id</th>
<th>address</th>
<th>operative id</th>
<th></th>
</thead>
<tbody>
</tbody>
</table>
In the javascript area of the blade template I have
<script type="text/javascript">
$(function () {
var table = $('.data-table').DataTable({
"iDisplayLength": 25,
"lengthMenu": [ [10, 25, 50,100,200, -1], [10, 25, 50,100,200, "All"] ],
columnDefs: [
{
targets: -1,
className: 'dt-right'
}],
processing: true,
serverSide: true,
ajax:"{{route('testData',['id' => $id])}}",
columns: [
{ data: 'jobID', name: 'jobID' , orderable: false, searchable: false},
{data: 'address', name: 'address'},
{data: 'operative_id', name: 'operative' },
{data: 'action', name: 'action', orderable: false, searchable: false},
],
});
});
</script>
In my controller I have this function:
public function testData (Request $request, $id)
{
$jb = DB::table('job')
->select('id AS jobID','operative_id','address')->where('operative_id',$id)->get();
return Datatables::of($jb)
->addColumn('action', function($pubs){
$btn = '<div style="float:right">
<i class="fas fa-book" ></i><i class="fas fa-edit" ></i></div>';
return $btn;
})
->make(true);
}
The controller (DatatablesController) has other functions that work perfectly and are much more complex, but I only want to show the jobs of the $id passed in. The error I am getting is a 500 error
Class App\Http\Controllers\DataTablesController does not exist
which of course it does.
For example this works perfectly:
public function allJobs(Request $request)
{
$user = Auth::user();
$cl = $user->client_id;
$jb = DB::table('job')
->join('job_status', 'job.jobStatus_id', '=', 'job_status.id')
->join('customers', 'job.customer_id', '=', 'customers.id')
->join('users', 'job.operative_id', 'users.id')
->where('job.client_id', $cl)
->select(['job.id as id', 'job_status.status as status', 'job.customer_id as customer_id', 'customers.customer as customer', 'users.name as operative','job.address as address','job.postcode as postcode','job.slug as slug','job_status.id as jobStatusID'])
->get();
return Datatables::of($jb)
->addColumn('action', function($pubs){
$btn = '<div style="float:right">
<i class="fas fa-book" ></i><i class="fas fa-edit" ></i></div>';
return $btn;
})
->make(true);
}
The route is defined as
Route::get('testData/{id}','DataTablesController#testData')->name('testData');
I just cannot see the way around it. Help is greatly appreciated!
I have worked it out. Basically the route cannot contain a parameter, so the {id} is dropped.
I placed a drop down box above the table and amended the javascript to
ajax:{
"url": "{{ route('allJobsData') }}",
"data": function(d) {
d.operativeChoice = $('#operativeChoice').val();
}
So if there is value in the select box this is sent via the ajax request to the controller. It is then just a case of playing with the controller code with an if statement.

Resources