Button click not working in Vue in datatable ajax render - laravel

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.

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

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

I need the data ,according to the type I send

My view blade that displays the data of all types but I need the specific type only, where i send it by ajax: "{{ route('taxonomies.json',type) }}".How do I send the type that I want from the given type?
<div class="table">
<table id="taxonomyTable">
<thead>
<tr>
<th>SN</th>
<th>Title</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="quickModal" tabindex="-1" role="dialog" aria-labelledby="quickModal" aria-hidden="true">
</div>
<input type="hidden" id="type" value="{{ $type }}" />
and the js is:
<script>
$(document).ready(function () {
var type = $('#type').val();
$('#taxonomyTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('taxonomies.json') }}",
columns: [
{
data: 'id',
render: function (data, type, row) {
return '<strong> #' + data + '</strong>';
}
},
{
data: 'title', name: 'title',
render: function (data, type, row) {
return '<strong>' + data + '</strong>';
}
},
{
data: 'parent', name: 'parent',
render: function (data, type, row) {
return '<strong>' + data.title + '</strong>';
}
},
{
data: 'type', name: 'type',
render: function (data, type, row) {
return '<strong>' + data.type+ '</strong>';
}
},
{
data: 'status',
render: function (data, type, row) {
return data === 'Active' ? '<button class="btn btn-outline-success btn-update-status" data-id="' + row.id + '">Active</button>' : '<button class="btn btn-xs btn-outline-danger btn-update-status" data-id="' + row.id + '">Inactive</button>';
}
},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
and my route is:
Route::get('/taxonomies/taxonomy-json/{type}', 'Admin\TaxonomyController#taxonomyJson')->name('taxonomies.json');
and my TaxonomyController has:
public function taxonomyJson()
{
$taxonomy = Taxonomy::with('parent')->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
The code mentioned above displays all of the types in the data but I only need the data of given type.Like my types are category, tag, videos,slider,etc and I need the data of types category only.
How can I fetch it?
Change You Input Hidden tag to which include whole route with it's parameters
<input type="hidden" id="type" value="{{ route('taxonomies.json', ['type' => $type]) }}" />
Now, In Your Ajax call pass input hidden type value directly to ajax as url.
var type_url = $('#type').val();
ajax: type_url
This way you don't have to worry about passing dynamic param. value to JS code from PHP code.
& In Your Controller Function
public function taxonomyJson($type=null)
{
$taxonomy = Taxonomy::with('parent')
if ($type) {
$taxonomy = $taxonomy->where('type', $type);
}
$taxonomy = $taxonomy->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
From your question as far I understood that you want filtered data, in order to get filtered data you needed to pass a filter type which you must use to filter your query. Here is an example for you
if ($request->ajax()) {
$users = User::select(
'users.id',
'users.name',
'users_details.first_name',
'users_details.last_name',
'users.email',
'users.membership_no',
'users.is_active',
'users.created_at'
)
->leftJoin('users_details', 'users.id', '=', 'users_details.users_id')
->where('user_group', '<>', 'admin')
->where(function ($query) use ($request) {
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
if (isset($genery) && $genery) {
$query->where('users_details.genre', $genery);
}
if (isset($varsitySession) && $varsitySession) {
$query->where('users_details.varsity_session', $varsitySession);
}
if (isset($yearOfPassing) && $yearOfPassing) {
$query->where('users_details.year_of_passing', $yearOfPassing);
}
if (isset($department) && $department) {
$query->where('users_details.department', $department);
}
if (isset($bloodGroup) && $bloodGroup) {
$query->where('users_details.blood_group', $bloodGroup);
}
if (isset($membership) && $membership) {
$query->where('users_details.membership', $membership);
}
if (isset($request->requested) && $request->requested == 0) {
$query->where('users.membership_no', $request->requested);
}
})
->get();
return Datatables::of($users)
->editColumn('name', function ($users) {
return ($users->first_name) ? $users->first_name . ' ' . $users->last_name : $users->name;
})
->editColumn('is_active', function ($users) {
return ($users->is_active) ? 'Active' : 'De-active';
})
->editColumn('membership_no', function ($users) {
return ($users->membership_no) ? $users->membership_no : 'Not Assigned';
})
->editColumn('created_at', function ($users) {
return $users->created_at->toDayDateTimeString();
})
->make(true);
}
Here you can see that I'm generating a query with where clause which are generated from request data
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
Here genere,varsity_session,year_of_passing,department,blood_group,membership are my filter data I'm sending with request.
here is my data table code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
processing: true,
serverSide: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data': function (d) {
d.genere = $("#genere").val();
d.varsity_session = $("select[name = varsity_session]").val();
d.year_of_passing = $("select[name = year_of_passing]").val();
d.department = $("select[name = department]").val();
d.blood_group = $("input[name = blood_group]").val();
d.membership = $("select[name = membership]").val();
d.paymentStatus = $("select[name = paymentStatus]").val();
d.requested = $("select[name = requested]").val();
}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
And my Static Html code
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="display compact dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Membership No</th>
<th>Status</th>
<th>Versity Session</th>
<th>Due Amount</th>
<th>Paid Amount</th>
<th>Created At</th>
<th>Last Transaction</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- /.col-lg-12 -->
</div>

Laravel Yajra DataTable - Fetch content via Ajax with supplied search parameters

After searching as to how to fill up a Yajra DataTable with data from an ajax call with user supplied search parameters, I came to this page for the official documentation.
It has a code snippet as follows...
$builder->ajax([
'url' => route('users.index'),
'type' => 'GET',
'data' => 'function(d) { d.key = "value"; }',
])
However, I cannot make anything out of it. Where does the $builder variable come from? How do I use the data received from the Ajax call to fill up the table? This page lists the callback functions with no details.
What I need
A full-blown example of how to fill up my data table with data received from an Ajax call initiated by the search button #btn_search after selecting a value from the drop-down #param.
For simplicity, lets assume that the table structure looks like...
<select id="param">
<option value="">Select </option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn_search" value="Search">Search</button>
<table>
<thead>
<tr>
<th>Serial</th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
</table>
The controller method that returns the data...
<?php
public function getBasicData()
{
$users = User::select(['id','name','email','address']);
return Datatables::of($users)->make();
}
The user selects a value from the dropdown and clicks on the search button. In the actual scenario, several dropdowns are there to collect the search parameters. Relevant jQuery code is...
$("#btn_search").click(function() {
var param_value = $("#param").val().trim();
// make ajax call probably
});
How can I make the Ajax call inside the click handler and fill up the data table with the received data?
The $builder variable is the class id of the table that would view the information ,
Here is an example :
<table id="data" class="table table-bordered table-hover" >
<thead>
<tr class="table-head">
<th>#</th>
<th>namr</th>
<th>email</th>
<th>date</th>
<th>auth</th>
<th>control</th>
<th>control</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<th> </th>
<th> </th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tfoot>
</table>
and this is ajax code
<script type="text/javascript">
var lastIdx = null;
var table = $('#data').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('/adminpanel/users/data') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'admin', name: 'isadmin'},
{data: 'edit', name: 'edit', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
"language": {
"url": "{{ Request::root() }} /admin/cus/Arabic.json"
},
"stateSave": false,
"responsive": true,
"order": [[0, 'asc']],
"pagingType": "full_numbers",
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: 25,
fixedHeader: true,
"oTableTools": {
"aButtons": [{
"sExtends": "csv",
"sButtonText": "ملف إكسل",
"sCharSet": "utf16le"
},
{
"sExtends": "copy",
"sButtonText": "نسخ المعلومات",
},
{
"sExtends": "print",
"sButtonText": "طباعة",
"mColumns": "visible",
}
],
"sSwfPath": "{{ Request::root() }} /website/admin/cus/copy_csv_xls_pdf.swf"
},
"dom": '<"pull-left text-left" T><"pullright" i><"clearfix"><"pull-right text-right col-lg-6" f > <"pull-left text-left" l><"clearfix">rt<"pull-right text-right col-lg-6" pi > <"pull-left text-left" l><"clearfix"> '
,initComplete: function ()
{
var r = $('#data tfoot tr');
r.find('th').each(function(){
$(this).css('padding', 8);
});
$('#data thead').append(r);
$('#search_0').css('text-align', 'center');
}
});
table.columns().eq(0).each(function(colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
});
table.columns().eq(0).each(function(colIdx) {
$('select', table.column(colIdx).header()).on('change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
$('select', table.column(colIdx).header()).on('click', function(e) {
e.stopPropagation();
});
});
$('#data tbody')
.on( 'mouseover', 'td', function () {
var colIdx = table.cell(this).index().column;
if ( colIdx !== lastIdx ) {
$( table.cells().nodes() ).removeClass( 'highlight' );
$( table.column( colIdx ).nodes() ).addClass( 'highlight' );
}
} )
.on( 'mouseleave', function () {
$( table.cells().nodes() ).removeClass( 'highlight' );
} );
</script>
this is a full table with ajax example ,like Yajara documentation help .

Resources