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

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

Related

Datatables adding search by column changes the size of table

I addedd <tfoot> on my table and the table is like 2x bigger more than before:
<div class="container">
<table class="table table-bordered" id="users-table" style="white-space: nowrap; margin: auto;">
<thead class="table-primary">
<tr>
<th>First Name</th>
<th>Verified Status</th>
<th>User Type</th>
<th>Birthdate</th>
<th>Email</th>
<th>Fiscal ID</th>
<th>Actions</th>
</tr>
</thead>
<tfoot class="table-info">
<tr>
<th>First Name</th>
<th>Verified Status</th>
<th>User Type</th>
<th>Birthdate</th>
<th>Email</th>
<th>Fiscal ID</th>
</tr>
</tfoot>
</table>
</div>
this is the script for datables:
<script>
$(function() {
$('#users-table').DataTable({
processing: false,
serverSide: true,
columnDefs: [
{"className": "dt-center", "targets": "_all"}
],
ajax: '{{ route('admin.users-data') }}',
columns: [
{ data: 'user', name: 'user' },
{ data: 'email_verified_at', name: 'users.email_verified_at',
render: function( data, type, full, meta ) {
if (data == null) {
return "<img class=\"\" src=\"{{ asset('images/icons/no.png')}}\" style=\"width:20%\"/>";
} else {
return "<img class=\"\" src=\"{{ asset('images/icons/yes.png')}}\" style=\"width:20%\"/>";
}
}
},
{ data: 'role', name: 'roles.role' },
{ data: 'birthdate', name: 'birthdate' },
{ data: 'email', name: 'email' },
{ data: 'fiscal_id', name: 'fiscal_id' },
{ data: 'action', name: 'action', orderable: false, searchable:false }
],
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
});
});
</script>
When I added footer on table for searching by column the size of the table change, its twice bigger and it does not accept any style on it.
Can someone explain why this is happening, thanks!
In 4 questions I've made in stavkoverflow, in all 4 of them I answered to myself...
Anyway, who is struggling with this just add this to your css:
tfoot input {
width: 100%;
}
Happy coding!

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.

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.

JSON showing instead of Datatable following Ajax call to Laravel Controller

I’m fairly new to ajax and json and would really appreciate some help.
I’m making an Ajax call to a Laravel Controller to return some fields from a database table called "subjects" and display them in a DataTable in a Laravel View. The problem is that when I open the view, what is see is JSON rather than the Datatable.
Here’s what’s returned in the view subjects/index:
{"draw":0,"recordsTotal":8,"recordsFiltered":8,"data":[{"id":"1","name":"Biology"},{"id":"3","name":"English Language"},{"id":"4","name":"Physics"},{"id":"5","name":"Chemistry"},{"id":"6","name":"Mathematics"},{"id":"7","name":"Mathematics"},{"id":"8","name":"English Language"},{"id":"9","name":"French"}],"queries":[{"query":"select count(*) as aggregate from (select '1' as `row_count` from `subjects`) count_row_table","bindings":[],"time":4.65},{"query":"select `id`, `name` from `subjects`","bindings":[],"time":0.41}],"input":[]}
Here’s the HTML in the view /subjects/index
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here’s the code in the Laravel Controller:
class SubjectsController extends Controller
{
public function index()
{
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
}
Here’s the code making the Ajax call:
$('#subjects_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{route('subjects.index')}}",
"columns":[
{"data": "id"},
{"data": "name"}
]
});
Here’s the route definition in web.php:
Route::get('subjects/', 'SubjectsController#index')->name('subjects.index');
Any help you can provide would be really appreciated
You should try this:
Routes
Route::get('subjects', 'SubjectsController#index')->name('subjects.index');
Route::get('getsubjects', 'SubjectsController#getSubjects')->name('subjects.get');
SubjectsController
class SubjectsController extends Controller
{
public function index()
{
return view('subjects.index');
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
public function getSubjects()
{
return \DataTables::of(Subject::query())->make(true);
}
}
View
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#subjects_table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('subjects.get') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
]
});
});
</script>

Resources