Laravel + datatable+ progress bar real time - laravel

i use datatable net and yajra/laravel-datatables
I need to organize the work in this way. The "load" button sends a request for calc all the data. The calculation should be done without waiting for the result of the execution of the request for calculation from the page. And the state of the calculation must be displayed in real time in the progress bar.
In case the “load” button is pressed, the current calculations should stop and restart.
If the page has been closed, the calculations should be stopped.
I assumed that this can be done using "JOBS" + "laravel echo". But how in the “JOBS” to follow that the page has been closed or the button has been pressed. And I don’t know how to do it more correctly.
my code now
table = $('#table').DataTable({
processing: true,
searching: true,
iDisplayLength: 50,
bStateSave: true,
order: [[0, "asc"]],
dom:
"<'row'<'col-sm-4'l><'col-sm-2'B><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
renderer: 'bootstrap',
ajax: {
url: "{{ route('data.tables.get.data') }}",
type: 'POST',
"headers": {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
"data": function (d) {
d.start_date = moment.unix(start_date_pic).format("YYYY-MM-DD");
d.end_date = moment.unix(end_date_pic).format("YYYY-MM-DD");
}
},
autoFill: true,
columns: [
{data: 'id', name: 'id', orderable: true,searchable: false},
{data: 'name', name: 'name', orderable: true,searchable: false},
}
});

Related

How to pass user_id in ajax route datatable Laravel

I have a datatable in Laravel, here is my code
$(function() {
var user_id = $(this).data('user_id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
processing: true,
serverSide: true,
ajax: "{{ route('detail.user', 'user_id')}}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'kpi',
name: 'kpi'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
$('body').on('click', '.detailProduct', function() {
...
});
$('#saveBtn').click(function(e) {
...
});
$('body').on('click', '.deleteProduct', function() {
...
});
});
I want to get user_id value from url parameter (ex: http://127.0.0.1:8000/detail/1000000004 ), I've tried code above, but it will return empty value.
Seems like I write wrong code to get url parameter. Because, If I change the ajax: "{{ route('detail.user', 'user_id')}}", into ajax: "{{ route('detail.user', '1000000004')}}", the program will works as expected. What sould I do? thanks in advance
You can not set variable in PHP code using JavaScript. You should not use PHP code on dynamic JavaScript code. There are 2 alternatives :
Use static path instead of Laravel route, just change ajax: "{{ route('detail.user', 'user_id')}}" to ajax: "/detail/"+user_id
Send user_id variable using Laravel blade view arg. on your controller define user_id like below:
return view('index',
['user_id', 1000000004]
);
then call it on the blade as php variable ($user_id) example ajax: "{{ route('detail.user', $user_id)}}"
be sure url in routes/web.php, provide one variable passing, ex /name-routes/{id}
and then in your controller function take the data id, function function_name($id){ }
and the last be sure format return json with format be like { data : [ name : "value name 1", name : "value_name2" ] }

Unknown paramater name when calling data in datatable

When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Here is My controller
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = Post::select(DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();
return Datatables::of($data)
->addIndexColumn()
->make(true);
}
return view('task.index',);
}
Here is 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: 'total',
name: 'total',
orderable: false,
},
{
data: 'finish',
name: 'finish'
},
]
});
});
</script>
When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Is something wrong in my controller or my view? thanks in advance
use this query
$data = DB::table('posts')->select('name', DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();

How to use HasManyThrough Relation in laravel datatable

I have three tables i am able to use relation between 2 tables easily. But when i am trying to access values from third table i mean trying to use hasManyThrough relation it is showing me always error. Do you have any idea how i can get value of third table column using middle table relation with first and last table.
System details
Linux
PHP 7
Laravel 5.3
Laravel-Datatables Latest Version
$('#mms-table').DataTable({
processing : true,
serverSide: true,
lengthMenu: [10,25,50,100],
order: [[1,'desc']],
ajax: '{!! url(LaravelLocalization::getCurrentLocale()."/admin/contact-management/contact-data") !!}',
columns: [
{ data: 'merchant.bank.name', name: 'merchant.bank_id', orderable: true },
{ data: 'merchant.merchant_id', name: 'merchant.merchant_id', orderable: true },
{ data: 'merchant.merchant_name', name: 'merchant.merchant_name', orderable: true },
{ data: 'contact.name', name: 'contact.name', orderable: true },
{ data: 'contact.email', name: 'contact.email', orderable: true },
{ data: 'city', name: 'city', orderable: true },
{ data: 'agent.name', name: 'agent.name', orderable: true },
{ data: 'action', name: 'action', orderable: false, searchable: false},
],
dom: 'Blfrptip',
buttons: [
{
extend: 'colvis',text: 'Show/Hide Columns'
}
],
oLanguage: {
sProcessing: "<img height='80' width='80' src='{{ url('public/images/loading.gif') }}' alt='loader'/>"
},
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();
});
});
}
});

Datatables ajax reload is ignoring dynamically updated request parameters

I am using server side jquery datatable 1.10.16. I am want to reload the data by requesting the datatable ajax with updated parameters.
To reload the datatable I am using the below datatable api:
$('#user_data').DataTable().ajax.reload();
My datatable initailization is given below:
$('#user_data').DataTable({
// to hide search filter
"searching": false,
"lengthMenu": [[5, 25, 50], [5, 25, 50]],
processing: true,
serverSide: true,
ajax: {
"url": '/admin/getStats',
"data": {user_id: user_id, date_range: JSON.stringify(DATE_RANGE)},
},
columns: [
{data: 'name', name: 'name'},
{data: 'date', name: 'date'},
{data: 'country', name: 'country'}
]
});
DATE_RANGE and user_id are global variables which are updated like this:
$('#dateSelector').on('apply.daterangepicker', function(ev, picker) {
DATE_RANGE[0] = picker.startDate.format('DD-MM-YYYY');
DATE_RANGE[1] = picker.endDate.format('DD-MM-YYYY');
console.log(DATE_RANGE); // here I am getting updated value properly
// reloading the datatable , but the parameters are the previous one
$('#user_data').DataTable().ajax.reload();
});
How to pass updated parameters ?
Disable caching for the table in the oSettings [this param is changing based on the DT version. Refer documentation of the version you are using.]
After calling
table.ajax.reload();
call this immediately:
table.ajax.clearAjaxParams();
Again this changes with version based. Refer documentation.
Finally solved it somehow. In future people may need:
$(document).ready(function() {
fetchData();
});
function fetchData() {
$('#user_data').DataTable({
// to hide search filter
"searching": false,
"lengthMenu": [[5, 25, 50], [5, 25, 50]],
processing: true,
serverSide: true,
ajax: {
"url": '/admin/getStats',
"data": {user_id: user_id, date_range: JSON.stringify(DATE_RANGE)},
},
columns: [
{data: 'name', name: 'name'},
{data: 'date', name: 'date'},
{data: 'country', name: 'country'}
]
});
}
$('#dateSelector').on('apply.daterangepicker', function(ev, picker) {
.....
....
$('#user_data').DataTable().destroy();
fetchData();
});
I think if you just redraw the dataTable, a new post request with the updated parameters will be sent to the server.
$('#dateSelector').on('apply.daterangepicker', function(ev, picker) {
$('#user_data').DataTable().draw();
}

Get all updated and newly created models together in a single url in server side

I am Using Kendo grid with batch edit. I want to get all Modified and newly created models together in a single url.
Say I have created 3 new row and also updated/edited 2 existing row in grid. Data source makes a HTTP request for every CRUD operation . The changed data items are sent by default as models and hit URL as I declared in “create” and update (transport) section of transport in datasource.I am getting models those are Modified (updated) in URL declared for ‘update’ in server side. And also find models those are newly created in URL declared for ‘create’….But I want to get all Modified and newly created models together in a single url.Is it possible to get all of the (both all modified and newly created) in a single URL?
Here is my Code for better understand.
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "LoadPerMeterCostsGridData",
type: "POST",
contentType: "application/json",
dataType: "json"
},
update: {
url: "UpdatePerMeterCostsData",
contentType: "application/json",
type: "POST",
dataType: "json"
},
create: {
url: "CreatePerMeterCostsData",
contentType: "application/json",
type: "POST",
dataType: "json",
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
serverPaging: false,
pageSize: 10,
batch: true,
schema: {
model: {
id: "PerMeterCostID",
fields: {
PerMeterCostID: { editable: false },
DrillBitSizeID: { editable: true },
Form: { editable: true },
To: { editable: true },
PerMeterCost: { editable: true },
ContractID: { editable: false }
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "grid");
}
},
editable: true,
pageable: {
refresh: true,
pageSizes: true
},
toolbar: ["create",
"save",
"cancel"
],
sortable: true,
autoBind: false,
columns:
[
{ field: "PerMeterCostID", width: 50, hidden: true, title: "ID" },
{ field: "DrillBitSizeID", width: 100, hidden: true, title: "Consumable" },
{ field: "Form", width: 100, title: " Form " },
{ field: "To", width: 50, title: "To" },
{ field: "PerMeterCost", width: 100, title: "Per Meter Cost" },
{ field: "ContractID", width: 100, hidden: true, title: "ContractID" },
{ command: ["destroy"], title: "Action", width: "175px" }
]
});
$("#grid ").data("kendoGrid").dataSource.read();
You can set each CRUD action to use the same url, but using the same url: property for both Create and Update. However you will still minimally get TWO requests (albeit to the same url)
update: {
url: "UpdateOrCreateAction",
},
create: {
url: "UpdateOrCreateAction",
},
this is because internally the dataSource pushes all "new" items as defined by "items an Id Field set to the default value for the field" in an array, and all items with dirty set to true into a different array. Kendo then sends both arrays back to the server according to the url for the action. (something like this i'd imagine)
if ( model.isNew())
createdPile.push(model)
else if ( model.dirty === true)
updatedPile.push(model)
//send both piles to the server
The "easiest" way to avoid this is to make sure your new objects explicitly set their id fields to something other then the default, and set the models dirty prob to true.
you could do this by using the edit event to override the actions
grid.bind('edit', function(e){
if ( e.model.isNew() ) {
e.model.id = -1; //
e.dirty = true;
console.log(e.model.isNew()) // should be false
}
})
this is probably an extreme amount of overkill to avoid one additional request, and prone to error. I would advise that you use the same url for both actions, and just accept that you will get the created items in one batch, and the updated in another.

Resources