Zend Framework 2: Populate ajax table (DataTable) - ajax

Below is snippet of table-ajax.js file from DataTable module.
My question is what will be Ajax url instead of table_ajax.php if I use IndexAction{} in my Controller. I want to display data from database.
var handleRecords = function () {
var grid = new Datatable();
grid.init({
src: $("#datatable_ajax"),
onSuccess: function (grid) {
},
onError: function (grid) {
},
onDataLoad: function(grid) {
},
loadingMessage: 'Loading...',
dataTable: {
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[10, 20, 50, 100, 150, -1],
[10, 20, 50, 100, 150, "All"] // change per page values here
],
"pageLength": 10, // default record count per page
"ajax": {
"url": "table_ajax.php", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});

Firstly you'll need to add a strategy to your viewmanager so you can return json. This is done within your module.config like so:
'view_manager' => array(
...
'strategies' => array(
'ViewJsonStrategy'
),
...
),
I'll just assume you have this DataTableModule imported via your Autoloader. So you can extend or implement the "table_ajax.php" within your controller and override/add a return value as a zf2 JsonModel.
In your Action within your Controller that extends/implements ajax_table.php
...
return new JsonModel($whateverTheResultIs);
...
Now that you have a controller that returns your JSON you'll require to set up a route. This is pretty straight forward it only links to your controller action and since you defined a strategy in your Viewmanager ZF2 does the rest of the pesky ajax stuff for you.
Edit: Rather then extending the table_ajax.php in your controller it probably is a good idea to write a Service which retrieves the information from table_ajax.php.

Related

How to search in Laravel Datatables results greater than a number and not by exact matches?

I have a Laravel project where I use DataTables to list some results from the database. Every result has width and height stored in the database. How to perform a search query where I am not looking for exact results, but for results that are greater than the added number?
For example if I search a width of 100 then I want to get all results that are greater than 100 -> 101, 102 etc.
This is my controller:
public function datatable()
{
$data = Unit::with('type')->get();
$datatable = DataTables::of($data)
->editColumn('type', function($model){
return $model->type->name;
})
->make();
return $datatable;
}
And this is the JS:
var datatableColumns = [
{ data: 'name' },
{ data: 'width', width: '1%' },
{ data: 'height', width: '1%' },
{ data: 'type', width: '1%' },
];
$('#datatable').dataTable({
processing: true,
serverSide: true,
ajax: $('#datatable').data('src'),
columns: datatableColumns,
});
At the moment if I search for 100 I am only getting results that has a width of 100
There are many ways to deal with this...
This is how I would do it. On your page with the datatables create a post form for things you are searching for. Use ajax post to your controller data endpoint. From here you can work the logic of your searches. So in this case it's just a matter of seeing the request that is 100 and you can build your eloquent statement per the request from the front.
So your eloquent would be something like this...
$data = Unit::where('width', '<', $request->width)->with('type')->get();
Obviously you can do some data shaping before it gets to you eloquent statement and just use a variable from logic before you do the query.

Django / Ajax / Datatable

I am trying to use following code in order to make a GET request to my django-based local server & render the obtained JSON-formatted data as a table:
$(document).ready(function (){
var rows_selected = [];
var table = $('#example').DataTable({
'ajax': $("#active_subscriptions_url").attr("data-ajax-target"),
'cache': true,
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'width':'1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'cache': true,
'rowCallback': function(row, data, dataIndex){
// Get row ID
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}
});
Unfortunately, it can not properly refer to the data, because each time this AJAX function adds a timestamp ad the end of a url:
http://127.0.0.1:8000/accounts/?_=1530637137189
I can not get rid of it - I have tried using 'cache' paremeter in Ajax, but it does not work.
Moreover, I ve tried to extend my urls.py with following position:
url(r'^accounts/(?P<timestamp>\?_=[0-9]*)/$', ShowSubscriptions.as_view(), name='show_subscriptions'),
But it does not match the coming request at all.

Custom rowCount for jquery bootgrid?

Hi I use in my project bootgrid I did custom lenght dropdown, evrithing is working apart the table pagination Is there a whay this to be fixed? Here is my code:
var $table = $("#data-table");
$table.bootgrid({
ajax: true,
url : 'myfancyurl',
columnSelection : false,
templates: {
//header: "" //Removes default bootgrid header
},
css : {
icon: 'md icon',
iconColumns: 'md-view-module',
iconDown: 'md-expand-more',
iconRefresh: 'md-refresh',
iconUp: 'md-expand-less'
},
labels :{
all:'',
loading:''
},
requestHandler: function (request) {
request.searchPhrase = $("#search-phrase").val();
request.rowCount = parseInt($('#row-count li.active').text());
return request;
}
}
});
$('#row-count li').on('click', function(e){
$('#row-count li').removeClass('active');
$(this).addClass('active');
$('.row-count').text( $(this).text() );
$table.bootgrid("reload");
});
So when I change lenght on backend side works fine, but the bootgrid doesn't recalc pagination when I pass the rowCount from request. Thanks in advance if someone can help.
I don't understand your question correctly.
You can add custom rowCount using the rowCount property
var $table = $("#data-table");
$table.bootgrid({
ajax: true,
url : 'myfancyurl',
columnSelection : false,
**rowCount: [10, 25, 33, 50, 66, 100],**
templates: {
//header: "" //Removes default bootgrid header
},...
and then in the backend you can use the request param
rowCount= request.args.get('rowCount', 33)

Kendo grid data source update approach not working

I have JSON data flowing via Pusher to a simple MVC5 website housing a Kendo Grid. The data, upon arrival, renders successfully in the grid however I'm creating and setting the data source every time. As this seems sinful, I'm trying to determine why my approach to simply updating the data source doesn't render the data.
The grid:
<div id="dashboard"></div>
<script>
$(document).ready(function () {
$("#dashboard").kendoGrid({
columns: [
{ field: "SystemName", width: "50px", title: "System" },
{ field: "Description", width: "100px", title: "Description" },
{ field: "SystemStatus", width: "30px", title: "Status" }
],
height: 600,
scrollable: true,
sortable: true,
});
var dataSource = new kendo.data.DataSource();
var grid = jQuery("#dashboard").data("kendoGrid");
grid.setDataSource(dataSource);
})
</script>
My failed attempt to read in the data without creating and binding a new data source (body of a function call which does happen):
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data = array;
grid.dataSource.read(array);
grid.refresh();
I have confirmed that the data arrives from Pusher correctly yet the above approach does not update the grid.
Thanks in advance for any consideration.
jbt
Use the data() method on the dataSource to set it's data.
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data(array);
You can only set the string value of data on the dataSource if the source is of XML type. Since you are using JSON, you need to call the data function and pass in the new data.
See documentation... http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-data

jqGrid - edit data

I am quite new to jquery and jqgrid. I use ASP.NET WebForms. I am able to get some data prom server and show it in grid. I use PageMethods to get data from server. Usually my code is
function CreateGrid(){
$("#sestGrid").jqGrid({
datatype: GetData,
//toolbar: [true, "top"],
colNames: ['Name', 'Age'],
colModel: [
{ name: 'Name', index: 'Name', width: 170, align: 'left',
sortable: false, key: true },
{ name: 'Age', index: 'Age', width: 40, align: 'center',
sortable: false, editable: true },
],
ondblClickRow: function () {
var row_id = $("#sestGrid").getGridParam('selrow');
$('#sestGrid').editRow(row_id, true);
}
});
}
function GetData() {
PageMethods.GetSestevalniStevecData(GotData);
}
function GotData (data) {
$("#sestGrid").clearGridData(false);
for (var j = 0; j <= data.length; j++)
$("#sestGrid").jqGrid('addRowData', j + 1, data[j]);
}
So, now I would like to edit some data and post it to server. How can I do that using PageMethods? Should I use any other approach?
And one more thing. I checked the demos http://trirand.com/blog/jqgrid/jqgrid.html and in all edit examples you are able to edit only one row and then you have to save changes… Is it possible to edit more than one row and save all changes in one step?
Thanks all.
jqGrid is designed to be used together with ajax services. So if the user change the data of some row then the changes will be send to the server: to the URL which you configure through jqGrid parameter editurl. So the easiest way to implement row editing will be to include an ASMX web-service or a WCF service in you web site. It is not important whether you use ASP.NET WebForms, ASP.NET MVC or just pure HTML for your pages. So just choose the technology which you prefer and add the corresponding page to your site.
The ASMX or WCF should has a method with the signature like
public string MyDataEdit (string Age, string oper, string id)
(see this old answer for more information). The method should return the id of the new added item (the Name in your case) in case of Add operation.
One more small remark. You can change the definition of the ondblClickRow function from function() to function(row_id) and remove the line used getGridParam('selrow').
I used your example and changed it a bit:
ondblClickRow: function (rowid) {
if (rowid && rowid != lastsel) {
changedRows.push(rowid); //keep row id
jQuery('#jqgrid').editRow(rowid, true);
}
}
Under the save button click event:
$.each(changedRows, function () {
var row = $("#jqgrid").getRowData(this);
var Id = row['ID'];
var price = $(row['Price']).val(); //this is an input type
});
HTH someone :)

Resources