How to pass route parameter in datatable function in laravel - javascript

This is my first post please pardon me.
I have a page named messdata.blade.php .I want to update the data-table of this page for every term id.
My route will be like this
/admin/messdata/1,
/admin/messdata/2,
/admin/messdata/3.
Here 1,2,3 are the term id.I want to show the messdata in the data-table single.
Screen shot of the datatable
But though I change the id my data-table stuck on the first id and doesn't change.
This is my controller code.
public $termid=1;
public function showmess($id)
{
$this->termid=$id;
return view('foradmin.mess.messdata');
}
public function showmessdata()
{
$users= DB::select('select * from messes where termno = :termno', ['termno' => $this->termid]);
return Datatables::of($users)
->addColumn('action', function ($user) {
return "</span> OPEN";
})
->make(true);
}
This my data-table code in java-script.
<script>
var table;
$(function() {
table=$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('admin.messdatashow') !!}',
columns: [
{data:'id',name:'id',searchable: false},
{data: 'messno', name: 'messno' },
{data: 'startat', name: 'startat',searchable: false },
{data: 'finishat', name: 'finishat',searchable: false },
{data:'messfee',name:'messfee', searchable: false},
{data:'extrafee',name:'extrafee', searchable: false},
{data:'fine',name:'fine',searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
</script>
This is my route.
Route::get('admin/messdata/{id}','MessController#showmess')->name('admin.messdata');
Route::get('admin/messdatashow','MessController#showmessdata')->name('admin.messdatashow');

you can use $id = Request::segment(3) to get id from url

Related

jsGrid is not working correctly with data loading page by page

I am trying to get jsGrid working in a project but I am missing something since I can't make it to work correctly. I have read docs carefully several times.
The scenario is as follow:
An AJAX call for get a list of subregion
An AJAX call for get a list of countries (each time I click on pagination a new request should be made in order to get proper values)
From docs under controller section:
loadData is a function returning an array of data or jQuery promise
that will be resolved with an array of data (when pageLoading is true
instead of object the structure { data: [items], itemsCount: [total
items count] } should be returned). Accepts filter parameter including
current filter options and paging parameters when pageLoading is true.
So my PHP function return data in the "proper" format as expected, meaning:
{
data: [items],
itemsCount: [total items count]
}
I have created a Pastebin with the result I get when the AJAX call is made (for the countries result). I believe the data is right now. So, this is how my code looks like:
$(function () {
$.ajax({
type: "GET",
url: "/adminconsolejsgrid/subregion"
}).done(function (subregion) {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
filtering: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
pageLoading: true,
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "/adminconsolejsgrid/countries",
data: filter
});
}
},
fields: [
{name: "country_name", title: "Name", type: "text", width: 100, sorting: true},
{name: "country_abbr", title: "Code", type: "text", width: 5, sorting: true},
{
name: "subregion",
title: "SubRegion",
type: "select",
width: 100,
items: subregion,
valueField: "subregion_id",
textField: "subregion_name"
},
{type: "control"}
]
});
});
});
But still not working for me which mean I am not getting any values on the grid. This pic is an example of what I get:
What I am missing? Any help?

Refresh / Redraw Datatables over function

and i call the datatable over the function.
Here is my function :
function drawTable(yearParameter) {
var oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = yearParameter;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
And i have event change to call my function above and pass parameter on it.
How to reload the datatables? Cause right now datatables won't reload.
I try to use :
oTable.destroy();
oTable.draw();
It make datatables functionality not work. Like search, pagination etc.
Edit
Here is my change event :
$('#year-value').on('change', function(e) {
var yearParam = $('#year-value').val();
drawTable(yearParam);
});
How to handle that?
Thank you??
Please try
oTable.clear();
oTable.draw();
Also, can I see your change event? I can help you re-add the rows
UPDATE 2
Ok, you can't call DT constructor more than once. First thing what you want to do is to save DT object as global object.
function drawTable() {
if(!oTable)
{
oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = filterYearParam;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
}
else
{
oTable.ajax.reload().draw();
}
$('#year-value').on('change', function(e) {
filterYearParam = $('#year-value').val();
drawTable();
});
Try this, and then I can try making your year to work.

Lazy Load with Scrollable {Virtual:true} not working in Kendo UI Grid

I am facing an issue to implement lazy loading in kendo ui grid.
I added scrollable virtual property and backend server side code to handle it but issues is after adding scrollable property I am unable to see scroll bar in my Grid.
Even the selected rows (20 page size) disappears off the bottom of the grid into the hidden overflow area.
Here is my code.
var managecustomerGrid = $("#customerGrid").kendoGrid({
dataSource: {
schema: {
data: "results",
total : "totalRecords",
model: {
id: "SRNUMBER",
fields: {
SRNUMBER : {type: 'number'},
CUSTOMERNAME : {type: 'string'},
DATEPAID : {type: 'string'}
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 20,
batch: false,
transport: {
read: {
type: "POST",
url: "/customer/customer.cfc",
dataType: "json",
error: function (xhr, error) {
alert('Error In Getting Customer Information.');
}
},
parameterMap: function(options, type) {
return {
ntPageNumber: options.page,
ntRowLimit: options.pageSize,
vcSortOrder: JSON.stringify(options.sort),
vcFilterCondition: JSON.stringify(options.filter)
}
}
}
},
toolbar: kendo.template($("#template").html()),
height: 600,
scrollable: {
virtual: true
},
filterable: {
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
endswith: "Ends with",
eq: "Is equal to",
doesnotcontain: "Doesn't contain"
}
}
},
sortable: true,
columns: [
{ field: "SRNUMBER", title: "SR No.", width: "80px", template: "<span id='#=SRNUMBER#'>#=SRNUMBER#</span>"},
{ field: "CUSTOMERNAME", title: "Customer Name", width: "110px"},
{ field: "DATEPAID", title: "Date", width: "110px"},
{ command: ["edit","detail","cancel"], title: " ", title: "Actions", width: "130px", filterable: false, sortable: false}
]
});
Please let me know if any one find any issues. I am unable to get it.
The kendo grid does not really support Lazy Loading out of the box. It may be easier to instead just make a blank scroll-able grid (without paging), and then to populate the data with ajax calls. You can use $.merge() to append data to the data array with little to no impact on performance.
$.ajax({
url: '/getNextData',
data: { filter: 'foo', lastLoaded: $("#Grid").data("kendoGrid").dataSource.at($("#Grid").data("kendoGrid").dataSource.total()-1).ID },
dataType: "json",
success: function (newData) {
$("#Grid").data("kendoGrid").dataSource.data($.merge($("#Grid").data("kendoGrid").dataSource.data(), newData))
},
error: function (e) { console.log(e); }
});
In this ajax example I load the next data based on the current last item in the grid and a filter. I just append the response to the currently loaded data.
I faced the same issue, my problem was the controller code. Here I am posting my controller hoping it would help someone someday
public JsonResult GetJson(int? projectid,int skip, int take, int pageSize, int page)
{
using (sqlCon)
{
var myData = sqlCon.Query<Device>("Select * from workbook.dbo.TargetList", new { projectid = projectid });
var data = myData .Skip(skip).Take(pageSize).ToList();
var total = myData .Count();
var json = new { data = myData };
var jsonResult = Json(new {data= data, total= total}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
}

Refresh Kendo UI grid data by reading a variable

Grid reads data from a javascript variable.
$("#grid").kendoGrid({
dataSource: {
type: "text",
data: jsvar,
schema: {
model: {
fields: {
id: {type: "string", editable: false},
name: {type: "string"}
}
}
},
pageSize: 20
},
pageable: {
input: true,
numeric: true
},
//toolbar: [{text: "Add"}],
columns: [
{command: [{text: "Edit", click: showDetailse}, {text: "View", click: viewoneitm}], title: " ", width: "170px"},
]
});
Then I change value of this variable jsvar with ajax and wait for ajax response and after that when I refresh grid with
jQuery("#grid").data("kendoGrid").dataSource.read();
jQuery("#grid").data("kendoGrid").refresh();
The grid is not repopulated with new data and old data stays in grid. Please tell me how to refresh grid data.
This worked fine and grid used to refresh perfectly untill I proviced static data, but after I used ajax and then 'refresh' it failed to update
If jsvar contains an array, the Kendo data source will create a model for each array item, so if you modify the original array, it won't change the DataSource. If you want to change the data, you should do it like this:
grid.dataSource.data(jsvar);

add record function in Kendo UI grid is called many times

I am using this html code for Keno UI grid
function loadPhoneGrid(salesRepsId){
$("#phone-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_phones_sales_reps.php?salesRepsId="+salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_phone_number.php?salesRepsId="+salesRepsId,
type: "POST"
},
destroy: {
url: "operations/delete_phone.php",
type: "POST"
},
create: {
url: "operations/add_phone.php?salesRepsId="+salesRepsId,
type: "POST",
},
},
schema: {
data:"data",
total: "data.length", //total amount of records
model: {
id: "PhoneId",
fields: {
PhoneType: { defaultValue: { PhoneTypeId: 1, PhoneTypeName: "Work"} },
PhoneNumber: { type: "string" },
IsMainPhone: {type: "boolean", editalbe:true},
}
}
},
pageSize: 5,
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [
{
field:"PhoneType",
title:"Type",
editor: PhoneTypeDropDownEditor,
template: "#=PhoneType.PhoneTypeName#"
},
{
field: "PhoneNumber",
title:"Phone Number",
},
{
field: "IsMainPhone",
title:"Is Main",
width: 65,
template: function (e){
if(e.IsMainPhone== true){
return '<img align="center" src ="images/check-icon.png" />';
}else{
return '';
}
}
// hidden: true
},
{ command: "destroy", title: " ", width: 90 },
],
});
}
The code in the server side is (add_phone.php)
<?php
require_once("../lib/Phone.php");
$phone = array();
foreach($_POST as $name => $value){
$phone[$name] = $value;
}
Phone::AddPhoneNumber($_GET["salesRepsId"], $phone);
?>
For the first time, I added a new record. add_phone.php is calling once and everything is working fine. For the second time (with out refresh the page) when I try to add a new record, add_phone.php is called twice. One of them contains the first record which has been added to database before and the second is the new the data.
in the result I have 3 records ( 2 same data of first insert) and one new.
This an example to make it clear ( inspect the post request with firebug)
first click on save button (false, (111) 111-1111, 4,Fax) // after I enter this phone (111) 111-1111
second click on save button (false, (111) 111-1111, 4,Fax) in addition to (false, (222) 222-2222, 3,Work) // after I added this (222) 222-2222
Any help ??
May be your ajax request raise an error. You can see it by subscribing to the error event of your datasource.
In case of error, the data are not synchronized in your datasource. In your case, I think your dataitem stay in "dirty mode" so the datasource try to insert them for each synchronization...

Categories

Resources