delete users in yajra laravel datatables - laravel

hy, i'm new to laravel now using L5 and yajra/datatables plugin.when I click on delete button it gives an error "tokenMismatchException in VerifyCsrfToken.php line 53:"
my code is
controller.php
return Datatables::of($users)
->addColumn('action', function ($id) {
return '<button class="btn-delete" data-remote="localhost/blog/public/delete/' . $id->id . '">Delete</button>'; })
->make(true);
in view
<script>
$(function(){
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route("data") !!}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
$('#users-table').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
// confirm then
$.ajax({
url:'delete/{id}' ,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#users-table').DataTable().draw(false);
});
});
});
</script>
in route.php
Route::get('delete/{id}',array('as'=>'delete', 'uses'=>'EditController#delete'));
I take reference from Laravel yajra/Datatables action delete is not working
I tried this
$('#users-table').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
var id = $(this).attr('id');
alert(id);
$.ajaxSetup({
it gives "undefined"
its not working for me..please help..

you need to add the following in your html:
<meta name="csrf-token" content="{{ csrf_token() }}">
You should definitely take a look at this page to understand how this works: https://laravel.com/docs/5.2/routing#csrf-protection

The tokenMismatchException in VerifyCsrfToken.php line 53: error means that either your csrf token has expired or that you are not sending this to the server when doing a post request. I'm guessing the second.
When doing a ajax post request to the server you need to include a parameter _token in your data. You can get the current csrf token for this user using csrf_token().
Another option is to add X-CSRF-TOKEN header to your ajax setup. The Laravel documentation explains how to do this.

Related

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">

Datatable Custom Toolbar Not Working With Select2 CSS

This is the code
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<!-- problem lays here -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<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,
responsive: true,
ajax: "{{ route('users.index') }}",
dom: '<l<"toolbar">f>rtip',
initComplete: function(){
$("div.toolbar").html('<div style="float:left;margin-left:4px;"><select class="form-control select2bs4 select2-hidden-accessible trash_all" style="width:140px;height:32px;margin-left:10px;" data-select2-id="17" tabindex="-1" aria-hidden="true"><option selected="selected" data-select2-id="19">Bulk Actions</option><option data-select2-id="38" value="trashAll">Trash</option></select></div><div style="float:left;margin-left:20px;"><select onchange="window.location = this.options[this.selectedIndex].value" class="form-control select2bs4 select2-hidden-accessible download-doc" style="width:140px;height:32px;margin-left:10px;padding-bottom:5px"" data-select2-id="17" tabindex="-1" aria-hidden="true"><option selected="selected" data-select2-id="19" value="{{route('users.index')}}">Download</option><option data-select2-id="38" value="{{route('users.pdf')}}">PDF</option><option data-select2-id="39" value="{{route('users.excel')}}">XLS</option><option data-select2-id="39" value="{{route('users.word')}}">Doc</option></select></div>');
},
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'roles', name: 'roles'},
{data: 'status', name: 'status'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$("div.toolbar").css("float", "left");
$('#roles').select2({
ajax: {
url: '{{ url('searchrole') }}',
processResults: function(data){
return {
results: data.map(function(item){return {id: item.id, text: item.name} })
}
}
}
});
When I remove this code
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
Custom toolbar is working
But, when I let the code above exist, custom toolbar element is gone. I should make it exist because select2 not working if I remove code above.
You can display those select controls by doing this:
(1) Un-comment your select2.min.css resource again.
(2) Remove this class from your code: select2-hidden-accessible. It appears in 2 places in your initComplete function and is causing your controls to be hidden.
(There may be other tweaks you need to make, depending on how the remaining classes in that block of HTML code interact with the select2 CSS.)

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

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

My Datatable on Laravel 5.3 sometime error

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

Resources