Laravel Datatables - Invalid JSON response - laravel

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);

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'
},
],
});
});

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

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);
}

How to get the data for a DataTable from the Controller to View using Ajax

In my main controller, I have a function that gets the data from the database, formats it and output it as JSON. My problem now is how to display this data to the DataTable. Most examples I read have the data saved from a different file from the controller. I would for the data to be from a function in the controller. How do I call that function?
View (SampleView.php)
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>EmpID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$( document ).ready(function() {
var table = $('#example').DataTable( {
"ajax": "main/getDataFunction",
// "ajax": "getDataFunction",
// "ajax": "<?php echo base_url()."main/getDataFunction"; ?>",
// "ajax": { url: 'main/getDataFunction', type: 'POST' },
"bPaginate":true,
"bProcessing": true,
"pageLength": 10,
"columns": [
{ mData: 'EmpID' } ,
{ mData: 'FirstName' },
{ mData: 'LastName' }
]
});
});
</script>
Controller (Main.php)
function getDataFunction() {
$sampleData = $this->db->getSampleData();
$data = array();
foreach($sampleData as $key) {
array_push($data, array("EmpID" => $key->empID,
"FirstName" => $key->firstName,
"LastName" => $key->lastName));
}
$results = array("sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData"=>$data);
echo json_encode($results);
}
Output of echo json_encode($results)
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[{"EmpID":"1","FirstName":"JOHN","LastName":"DOE"}]}
I am not sure about DataTable but what you can do is you can use eval() to evaluate json data first and then fetch your json response values into view.
Old way which I knew is —
$.ajax(function() {
type : 'get', // or 'post',
data : {key:value},
dataType : 'json',
success : function(response){
var html_data = response.eval(); // this will serialize your data object
$('selector').val(html_data.name);
// $('selector').val(html_data.sEcho); as per your output of the code.
// or
$('selector').html(html_data);
}
});

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.

Button click not working in Vue in datatable ajax render

I am a newbie in Vuejs.
I have a users table which is showing data using Server-side processing in Datatable. I am trying to add a click event which will call a vue function. But the click function is not working at all. I tried use these methods. But none of them are working.
v-on:click="functionName"
v-on:click="$emit('functionName')"
#click="functionName"
HTML part
<table class="table table-bordered data-table dataTable-load">
<thead class="thead-light">
<tr>
<th style="width: 80px;">No</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Type</th>
<th>Created</th>
<th>Last Updated</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div>
<span v-html='data'></span>
</div>
SCRIPT part
var dt = $('.dataTable-load').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ url('user/getdata') }}",
type: "post",
data: {"_token": "{{ csrf_token() }}"}
},
columns: [
{name: 'id', data: 'id', },
{name: 'name', data: 'name'},
{name: 'email', data: 'email'},
{name: 'phone', data: 'phone'},
{name: 'usertype', data: 'usertype',
"render": function (data, type, row) {
if (row.usertype == 'M') {
return 'Manager';
} else {
return 'Staff';
}
}
},
{name: 'created_at', data: 'created_at'},
{name: 'updated_at', data: 'updated_at'},
{
title: 'msg',
"render": function (data, type, row) {
return '<button v-on:click="showModal" #click="showModal">the button</button>';
}
}
]
});
dt.on('order.dt search.dt', function () {
dt.column(0, {search: 'applied', order: 'applied'}).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
App.js
const app = new Vue({
el: '#app',
data: {
data: '',
},
methods: {
showModal() {
this.data = 'Now click on me <a href=\'#\' #click.prevent=\'alert("yo")\'> here </a>';
},
},
});
Please let me know how to do it correctly. Thanking you in advance.

Resources