My Datatable on Laravel 5.3 sometime error - laravel

I've been using Datatable on my Laravel project, but sometime when I refresh the page, it works and sometime it doesnt
This is my script on view
#section('script')
<script type="text/javascript">
$(function () {
var oTable = $('#tabel-stok').DataTable({
processing: true,
serverSide: true,
order: [[ 0 ,"desc"]],
ajax: {
url: '{{ url("data-stok") }}'
},
columns: [
{data: 'updated_at', name: 'updated_at'},
{data: 'nama_produk', name: 'nama_produk'},
{data: 'harga_satuan', name: 'harga_satuan'},
{data: 'jumlah_stok', name: 'jumlah_stok'},
{data: 'tambah', name: 'tambah', orderable: false, searchable: false},
{data: 'edit', name: 'edit', orderable: false, searchable: false}
],
});
});
</script>
#endsection
This is my controller
public function index()
{
return view('transaksi-masuk.transaksi-masuk');
}
public function dataStok()
{
$stok = Produk::all();
return Datatables::of($stok)
->addColumn('tambah', function ($stok) {
return '<span class="label label-primary">TAMBAH</span>';
})
->addColumn('edit', function ($stok) {
return '<span class="label label-warning">EDIT</span>';
})
->make(true);
}
And this is the error message
DataTables warning: table id=tabel-stok - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Is there any solution for this? Thank you

It works now. I tried to remove addColumn from controller and edit my script like this
columns: [
{data: 'updated_at', name: 'updated_at'},
{data: 'nama_produk', name: 'nama_produk'},
{data: 'harga_satuan', name: 'harga_satuan'},
{data: 'jumlah_stok', name: 'jumlah_stok'},
{
name: '',
data: null,
sortable: false,
searchable: false,
render: function (data) {
var actions = '';
actions += '<span class="label label-primary">TAMBAH</span>';
actions += '<span class="label label-warning">EDIT</span>';
return actions.replace(/:id/g, data.id_produk);
}
}
Thank you for helping me :)

Related

Display images from Database in Datatables using jQuery for a Laravel app

I have a table in Mysql database that stores hashed image names. The actual image is stored in the storage folder of the Laravel application with the same name as in the database. I want to display these images alongside other columns in the database for each item in the jQuery Datatable.
I was able to display a single image for all the Datatable rows with the code below.
var table = $('.pdata-tables').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('project.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'type', name: 'type'},
{data: 'description', name: 'description'},
{data: 'stack', name: 'stack'},
{data: 'image', name: 'image',
"render": function (data) {
return '<a href="{{ URL::asset("storage/project_images/2AA3BIA4wSk4DAeB8N8AP1MdXXhj5kFVtO27jKui.jpg") }}"><img src=" {{ URL::asset("storage/project_images/2AA3BIA4wSk4DAeB8N8AP1MdXXhj5kFVtO27jKui.jpg") }} " width="50px"/><a>' }},
{data: 'video', name: 'video'},
{data: 'year', name: 'year'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
Controller function
public function index(Request $request)
{
if ($request->ajax()) {
$data = Project::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<i class="p-1 zmdi zmdi-edit"></i>';
$btn = $btn.' <i class="p-1 zmdi zmdi-delete"></i>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin_pages.project', ['projects' => $this->projects, 'clients' => $this->clients]);
}
How can I display individual images for each row?
I got the solution with suggestion in the comment.
the code now looks like this.
var table = $('.pdata-tables').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('project.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'type', name: 'type'},
{data: 'description', name: 'description'},
{data: 'stack', name: 'stack'},
{data: 'image', name: 'image',
"render": function (data) {
return '<a href="{{ URL::asset("storage/project_images/' + data + '") }}"><img src=" {{ URL::asset("storage/project_images/' + data + '") }} " width="50px"/><a>' }},
{data: 'video', name: 'video'},
{data: 'year', name: 'year'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});

Yajra multi search filters

I am trying to assign a custom search box for each column of the table as shown in this example.
https://datatables.yajrabox.com/eloquent/multi-filter-select
But the code given for this was so confusing. I am not getting any idea how to use that code to achieve this.
Here is my code.
CONTROLLER FUNCTION
function leadManage(Request $request){
$lead_id = $request->get('id');
echo $lead_id;
if ($request->ajax() && $request->draw) {
$data = lead::select('leads.id', 'leads.fname', 'leads.lname', 'leads.phone', 'leads.email', 'leads.created_at', 'lead_status_lists.status_name', 'users.fname as user_fname', 'users.lname as user_lname');
$data = $data->join('users', 'leads.assigned_to', '=', 'users.id');
$data = $data->orderBy('leads.id', 'DESC');
$data = $data->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('date', function($row){
$date = date('d M Y', strtotime($row->created_at));
return $date;
})
->addColumn('action', function($row){
$btn = '<i class="fa fa-pencil font-14"></i>
<button class="btn btn-danger btn-sm" data-toggle="tooltip" data-original-title="Delete" onclick="return deletelead_conf('.$row->id.')"><i class="fa fa-trash font-14"></i></button>';
return $btn;
})
->rawColumns(['name','user_name','date','action'])
->make(true);
}
return view('admin.lead_manage');
}
View File script
$(document).ready(function() {
$('.dataTable').DataTable( {
processing: true,
serverSide: true,
ajax: "{{ route('lead.index') }}",
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
{data: 'name', name: 'name'},
{data: 'phone', name: 'phone'},
{data: 'email', name: 'email'},
{data: 'course_name', name: 'course_name'},
{data: 'user_name', name: 'user_name'},
{data: 'status_name', name: 'status_name'},
{data: 'date', name: 'date'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
I tried to add additional script from given url but it make table body empty and no error. Here is script from given url which I tried to add.
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();
});
});
}
But I am not getting any idea how to use those controller function (from given url) in my written code.

Load DataTable where select in Laravel 8 with yajra datatables

I need to load a DataTable where the input value equals the value in the database. I try to use this function but not work correctly.
Controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*')->where('shp_no_for_it', $shp_no)->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)"
class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
Script
$('#search_button').click(function(){
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('getit') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
});
Input
<input type="title" class="form-control" id="shp_no_for_it" name="shp_no_for_it">
Route
Route::get('getit', [ItemController::class, 'getit'])->name('getit');
Look like you have not passed data in ajax. So first create a function to datatable
function itemDataTable(param={}){
dataTable = $('#itemTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getit') }}",
type: 'get',
headers: { 'content-type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: param,
},
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
return dataTable;
}
Then on page load call data table
$(function () {
itemDataTable();
});
and on click search button
$('#search_button').click(function(){
var param={
shp_no_for_it:$('#shp_no_for_it').val();
}
itemDataTable(param)
});
and in controller if you are using server side processing then no need to call get() .But add following
processing: true,
serverSide: true,
and in controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*') ->where('shp_no_for_it', $shp_no);
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
and in html table
<table class="table table-bordered data-table col-md-12" id="itemTable">

Laravel Yajra DataTable Column Sorting not proper working

Laravel Yajra DataTable Column Sorting not proper working. If I use ->get() function in Query then DataTable sorting works fine. But I don't want to use get() function because If I have more than 100 000 records then it takes too much time so I don't want to use get() in query
here is my controllers code
$deals = Deal::orderBy('updated_at', 'desc');
$searcharray = array();
parse_str($request->fromValues,$searcharray);
if(isset($searcharray) && !empty($searcharray)){
if($searcharray['filtertype'] !=''){
$deals->where("deal_isApproved",'=',$searcharray['filtertype']);
}
}
$detail_data = $deals;
// print_r($deals);
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
$btn .= '<a class="dropdown-item" href="'.route('admin.deals.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<a deal_id="'.$data->id.'" class="dropdown-item deleteDeal" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
here is my datatable initialize in blade file
var dataTable = $('#example_laravel').DataTable({
//lengthMenu: getPageLengthDatatable(),
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
// responsive: true,
// // "responsive": true,
// "lengthChange": false,
// "autoWidth": false,
ajax: {
url: '{{ route("admin.deals.filter")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
data.fromValues = $("#filterdealtype").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'deal_title', name: 'deal_title'},
{data: 'deal_desc',
render: function (data, type, row, meta) {
var data = decodeHTMLEntities(data);
var data = data.replaceAll("href=\"","href=\"http://");
return '<div style="width: 340px; word-wrap: break-word;">'+data+'</div>';
},
},
{data: 'deal_price', name: 'deal_price'},
{data: 'deal_retail_price', name: 'deal_retail_price'},
{data: 'deal_percent_off', name: 'deal_percent_off'},
{data: 'deal_img',
render: function (data, type, row, meta) {
if(data){
return '<img id="myImg" src="{{ asset('') }}'+data+'" height="100px" width="100px">';
}else{
return '';
}
}
},
{data: 'deal_start_date', name: 'deal_start_date'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
output I get be like below image
I solve another problem related to sorting... I share answer of this for helping to other people,
Actually when I define orderby in controller than when I click on Datatable Column for sorting then it was not sorting, because when we click on column than it pass two times different different orderby field so its not works,
Solution of Problem
$deals = Deal::select('*');
if($request->order ==null){
$deals->orderBy('created_at', 'desc');
}
& Another problem about wrong sequence of sorting data issue faced because of wrong datatype in DataBase table...
So, Please also verify Datatype of Database
I hope its helps to you...
& thanks to you #ibrahim-dogan this guy for answer me about wrong Datatype...
thank you

Laravel Datatable addColumn returns ID of one record only

I'm trying to use Yajra Datatable to integrate a DataTable in my website. I was able to render the table but run into a problem. In the addColumn field where i put the delete option, the id is returning only the single record not the specific ID of each column.
Here's my controller code
public function fetchData($manifest_no){
$hwb_data = DB::table('hwb')
->join('manifest_records', 'hwb.id', '=', 'manifest_records.hwb_id')
->join('consignees', 'consignees.id', '=', 'hwb.client_id')
->where('manifest_records.manifest_no', $manifest_no)
->get();
return Datatables::of($hwb_data)
->addIndexColumn()
->addColumn('action', function($row){
$idx = $row->id;
$btn = "<a href='javascript:void(0)' id='delete' data-id='$idx' class='edit btn btn-danger btn-sm'>$idx</a>";
return $btn;
})
->rawColumns(['action'])
->make(true);
}
Here's the Datatable rendering
$(function () {
let table = $('#tableSample').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url("/fetchData/$manifest_no") }}",
columns: [
{data: 'id', name: 'id', 'visible': false},
{data: 'created_at', name: 'created_at'},
{data: 'hwb_no', name: 'hwb_no'},
{data: 's_name', name: 's_name'},
{data: 'c_name', name: 'c_name'},
{data: 'destination', name: 'destination'},
{data: 'dr_no', name: 'dr_no'},
{data: 'commodity', name: 'commodity'},
{data: 'actual_weight', name: 'actual_weight'},
{data: 'tp_cbm', name: 'tp_cbm'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$("#tableReload").delegate('#delete', 'click', function (e) {
e.preventDefault();
let id = $(this).data('id');
console.log(id);
})
});
I Whenever i render the data, i always run into this problem. Action button always have value of 2
I guess you have to use the Render function Like this, instead of the backend function
Also try to dump $row and the dd before rendering the view, just to check that $row has the correct values you are expecting!
$(function () {
let table = $('#tableSample').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url("/fetchData/$manifest_no") }}",
columns: [
{data: 'id', name: 'id', 'visible': false},
{data: 'created_at', name: 'created_at'},
{data: 'hwb_no', name: 'hwb_no'},
{data: 's_name', name: 's_name'},
{data: 'c_name', name: 'c_name'},
{data: 'destination', name: 'destination'},
{data: 'dr_no', name: 'dr_no'},
{data: 'commodity', name: 'commodity'},
{data: 'actual_weight', name: 'actual_weight'},
{data: 'tp_cbm', name: 'tp_cbm'},
{ data: 'id',
name: 'action',
orderable: false,
searchable: false,
"render": function ( data, type, row, meta ) {
return '<button class="delete btn btn-danger" data-id="'+ data +'"> Delete </button>'
}},
]
});
});
->addColumn('action', function($hwb_data){
$btn = "<a href='javascript:void(0)' id='delete' data-id='".$hwb_data->id."' class='edit btn btn-danger btn-sm'>".$hwb_data->id."</a>";
return $btn;
})
Try this, It worked for me

Resources