Export data from jqxgrid - jqxgrid

I want to export all data in my jqxgrid into json and send it to another page via AJAX.
My problem is when I click export button, the data in the grid and data before export was not the same. It change float number to Interger. Here is my code:
Javascript:
$('#export_bt').on('click', function(){
var row = $("#jqxgrid").jqxGrid('exportdata', 'json');
$('#debug').html(row);
console.log(row);
});
var tableDatas = [
{"timestamp":"06:00:00","A":99.49,"B":337.77,"C":155.98},
{"timestamp":"07:00:00","A":455.67,"B":474.1,"C":751.68},
{"timestamp":"08:00:00","A":1071.02,"B":598.14,"C":890.47}
];
var tableDatafields = [
{"name":"timestamp","type":"string"},
{"name":"A","type":"number"},
{"name":"B","type":"number"},
{"name":"C","type":"number"}
];
var tableColumns = [
{"text":"Times","datafield":"timestamp","editable":"false","align":"center","cellsalign":"center","width":150},
{"text":"A","datafield":"A","editable":"false","align":"center"},
{"text":"B","datafield":"B","editable":"false","align":"center"},
{"text":"C","datafield":"C","editable":"false","align":"center"}
];
function setTableData(table_data,table_column,table_datafields)
{
sourceTable.localdata = table_data;
sourceTable.datafields = table_datafields;
dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
$("#jqxgrid").jqxGrid({columns:table_column});
$("#jqxgrid").jqxGrid('updatebounddata');
$('#jqxgrid').jqxGrid('sortby', 'timestamp', 'asc');
$("#jqxgrid").jqxGrid('autoresizecolumns');
for(var i=0;i<table_column.length;i++){
$('#jqxgrid').jqxGrid('setcolumnproperty',table_column[i].datafield,'cellsrenderer',cellsrenderer);
}
}
var cellsrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
if (value||value===0) {
return value;
}
else {
return '-';
}
};
var sourceTable ={ localdata: '', datatype: 'array'};
var dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
dataAdapterTable.dataBind();
$("#jqxgrid").jqxGrid({
width: '500',
autoheight:true,
source: dataAdapterTable,
sortable: true,
columnsresize: false,
selectionmode: 'none',
columns: [{ text: '', datafield: 'timestamp', width:'100%' , editable: false, align:'center'}]
});
setTableData(tableDatas,tableColumns,tableDatafields);
Html:
<div id="jqxgrid"></div>
<button id="export_bt">Export</button>
<div id="debug"></div>
http://jsfiddle.net/jedipalm/jHE7k/1/

You can add the data type in your source object as below.
datafields: [{ "name": "timestamp", "type": "number" }]
And also I suggest you to apply cellsformat in your column definition.
{ text: 'timestamp', datafield: 'timestamp', cellsalign: 'right', cellsformat: 'd' }
The possible formats can be seen here.
Hope that helps

You can export data in very fast way just like it is id jqxGrid with
var rows = $("#jqxGrid").jqxGrid("getrows");
It will be json array.

Related

filter the ui grid value based on the row check box is selected

This is the ui grid code( minimal)
//js file
vm.gridOptions1 = {
enableColumnResizing: true,
enableAutoResizing: false,
columnDefs: [
{
field: 'createdDate',
displayName: 'Created Date',
type: 'date',
cellFilter: 'date:"dd-MM-yyyy"',
enableHiding: false, headerTooltip: 'Created Date'
},{
name: 'Refer',
displayName: 'Refer', enableSorting: false, headerTooltip: 'Refer',
cellTemplate: '<input type="checkbox" ng-model="row.entity.isReferred" />'
}
]});
On click of this byutton I need to filter, get only rows which check box is selected(isReferred = true)
//html file
<button type="button" class="btn btn-primary-joli " ng-click="srchctrl.send">Send</button>
This is the file trying to get the filtered list based on the redeffered check box value, but its not working.
//JS file
vm.send = function () {
if (vm.gridApi.selection.data != null && vm.gridApi.selection.data != undefined) {
vm.referredList = filterFilter(vm.gridApi.selection.data, {
isReferred: true
});
console.log("referredList :"+JSON.stringify(referredList));
}
};
How can I get all the value ticked. I don't want to invoke method on each click event on check box.
I think the easiest way to achieve this is by using the gridApi.grid.registerRowsProcessor function. I have adapted a Plunker to show what I mean:
http://plnkr.co/edit/lyXcb90yQ0ErUJnSH7yF
Apps.js:
var app = angular.module('plunker', ['ui.grid']);
app.controller('MainCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) {
$scope.gridOptions = {
columnDefs: [
{field: 'col1', displayName: 'Column 1', width: 175},
{field: 'col2', displayName: 'isReferred', width: '*'}
],
data: [
{ col1: "Hello 1",col2: true},
{ col1: "Hello 2", col2: false},
{ col1: "Hello 3", col2: true},
{ col1: "Hello 4", col2: false},
{ col1: "Hello 5", col2: true}
],
enableFiltering: true,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
$scope.Filter = Filter;
$scope.ShowAll = ShowAll;
function ShowAll() {
$scope.gridApi.grid.removeRowsProcessor(myFilter);
$scope.gridApi.core.queueGridRefresh();
}
function Filter() {
$scope.gridApi.grid.registerRowsProcessor(myFilter, 150);
$scope.gridApi.core.queueGridRefresh();
}
function myFilter(renderableRows) {
renderableRows.forEach( function(row) {
row.visible = row.entity.col2;
});
return renderableRows;
}
}]);
Clicking the Filter button will register the myFilter RowsProcessor, which will iterate through all rows to alter the visible attribute.
Clicking the ShowAll button will remove the RowsProcessor, thus showing all previously hidden rows again.
Whenever an isReferred value changes, the filter will cause the grid to automatically update this change.

Adding text to an Angular Ui-Grid date column

I have an angular ui-grid that has a column for a date, which indicates the date an email was sent to a new user:
{
name: "SentOn",
displayName: "Sent On",
cellFilter: "date:\"yyyy-MM-dd HH:mm\""
}
The email is not sent until a number of background processes are complete, so this date can be null. When the date is null, nothing shows in the cell.
Is there a straight forward way to display some default text when the date is null?
There are two ways you can achieve what you want here.
You can provide a custom template for the cell to handle the null date scenario. This is probably easier option too.
{
name: "SentOn",
displayName: "Sent On",
cellTemplate : "<div class=\"ui-grid-cell-contents\">{{COL_FIELD CUSTOM_FILTERS || \"Not Sent\"}}</div>"
}
Or you can create a custom cellFilter which will take care of the null date. You can extend the existing date filter to achieve this.
var app = angular.module('app', ['ngTouch', 'ui.grid','ui.grid.edit']);
var grid;
app.filter('customDate', function($filter){
var standardDateFilterFn = $filter('date');
return function(dateToFormat){
if(!dateToFormat)
return "Not Sent Yet";
return standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
}
});
app.controller('MainCtrl', ['$scope', function ($scope) {
var myData = [
{
id1:new Date(),id2:"2",id3:"3",id4:"4",id5:"5",
}, {
id1:null,id2:"2",id3:"3",id4:"4",id5:"5",
},]
var getTemplate = function()
{
return "<div class=\"ui-grid-cell-contents\">{{COL_FIELD CUSTOM_FILTERS}}</div>";
}
var cellEditable = function($scope){
if($scope.row.entity.oldId4===undefined)
return false;
return $scope.row.entity.oldId4!=$scope.row.entity.id4;
}
$scope.gridOptions = {
enableFiltering: true,
onRegisterApi: function(gridApi){
grid = gridApi;
},
data: myData,
columnDefs:[
{
field: 'id1',
displayName: "id1",
width: 200,
cellTemplate: getTemplate(),
cellFilter : "customDate:\"yyyy-MM-dd HH:mm\""
},
{
field: 'id2',
displayName: "id2",
width: 100
},{
field: 'id3',
displayName: "id3",
width: 100
},{
field: 'id4',
displayName: "id4",
width: 100
},{
field: 'id5',
displayName: "id5",
width: 100
},
],
}
$scope.gridOptions.onRegisterApi = function(gridApi){
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.edit.on.afterCellEdit($scope,function(rowEntity, colDef, newValue, oldValue){
rowEntity.oldId4 = oldValue;
$scope.$apply();
});
};
$scope.test = function()
{
window.alert("Cell clicked")
}
}]);
here is a working plnkr. http://plnkr.co/edit/qHaRzkzxGEphuTMQ6oqG?p=preview

Change angular ui-grid's columns visibility

I want to show/hide columns after the grid is rendered. Before i moved to the new ui-grid
I called to toggleVisible() but now it doesn't seem to work.
I tried to change the column def visibility(or any other property) like bellow
columnDefs[9].visible = false;
When I set the visibility on the column definition(before render) it does work, but after wards i cannot change it.
Old question, but this works for me in 3.0.0-rc.20. I'm guessing columnDefs needs to be in scope.
$scope.columnDefs = [
{ name: 'one' },
{ name: 'two', visible: false }
];
$scope.grid = {
data: 'data',
columnDefs: $scope.columnDefs
};
$scope.grid.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
};
$scope.showColumnTwo = function() {
$scope.columnDefs[1].visible = true;
$scope.gridApi.grid.refresh();
};
Just started working with angular-ui-grid so this might be not the best solution.
Try including the uiGrid api object and then invoking the refersh method on a grid object
...
$scope.gridOptions.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
};
....
columnDefs[9].visible = false;
$scope.gridApi.grid.refresh();
In case anyone was looking for a solution that didn't require you to create a columndDef.
s.gridOptions = {
data: 'myData',
onRegisterApi: function(gridApi) {
gridApi.core.registerColumnsProcessor(hideIdColumn);
s.gridApi = gridApi;
function hideIdColumn(columns){
columns.forEach(function(column){
if(column.field==='_id'){
column.visible=false;
}
});
return columns;
}
}
Just replace the column.field==='_id' part with your own condition.
Also don't forget to return the columns or you will not get any columns at all.
The answer from user3310980 was preferred when I saw it but there is very little documentation on the registerColumnsProcessor method. I found reference to his comment about using it without column definitions so I wanted to make it clear that you can certainly use this method with column defs. This provides for some interesting flexibility.
In this example, there are four columns that swap with four other columns determined by a toggle button. $ctrl.showDetails is true when sales columns should display and false when payment items should display.
In the column definitions, the onRefresh property is defined as a method to call for the column on grid refresh and the setVisibleColumns method is supplied to registerColumnsProcessor(). When the grid is refreshed, for each column, it will check the column definition in the colDef property and call the onRefresh method for each column that defines it, with this set to the column object.
/*--------------------------------------------*/
/* showPayments - Make payment items visible. */
/* showDetails - Make sales items visible. */
/*--------------------------------------------*/
var showPayments = function() { this.visible = !$ctrl.showDetails; };
var showDetails = function() { this.visible = $ctrl.showDetails; };
var columnDefs =
[
{ field: 'receiptDate', displayName: 'Date', width: 120, type: 'date', cellFilter: "date:'MM/dd/yyyy'", filterCellFiltered: true },
{ field: 'receiptNumber', displayName: 'Rcpt No', width: 60, type: 'number' },
{ field: 'receiptFrom', displayName: 'From', width: 185, type: 'string' },
{ field: 'paymentMethod', displayName: 'Method', width: 60, type: 'string', onRefresh: showPayments },
{ field: 'checkNumber', displayName: 'No', width: 60, type: 'string', onRefresh: showPayments },
{ field: 'checkName', displayName: 'Name', width: 185, type: 'string', onRefresh: showPayments },
{ field: 'paymentAmount', displayName: 'Amount', width: 70, type: 'string', onRefresh: showPayments },
{ field: 'description', displayName: 'Desc', width: 100, type: 'string', onRefresh: showDetails },
{ field: 'accountNumber', displayName: 'Acct No', width: 80, type: 'string', onRefresh: showDetails },
{ field: 'accountName', displayName: 'Acct Name', width: 160, type: 'string', onRefresh: showDetails },
{ field: 'salesTotal', displayName: 'Amount', width: 70, type: 'string', onRefresh: showDetails }
];
/*----------------------------------------------------*/
/* Columns processor method called on grid refresh to */
/* call onRefresh' method for each column if defined. */
/*----------------------------------------------------*/
var setVisibleColumns = function(cols)
{
for (var i=0; i < cols.length; i++)
if (cols[i].colDef.onRefresh)
cols[i].colDef.onRefresh.call(cols[i]);
return cols;
};
/*----------------------------------*/
/* Callback to set grid API in */
/* scope and add columns processor. */
/*----------------------------------*/
var onRegisterApi = function(api)
{
$ctrl.itemList.api = api;
api.core.registerColumnsProcessor(setVisibleColumns);
};
/*------------------------------*/
/* Configure receipt item grid. */
/*------------------------------*/
$ctrl.showDetails = false;
$ctrl.itemList =
{
columnDefs: columnDefs,
enableCellEdit: false,
enableColumnMenus: false,
enableFiltering: false,
enableHorizontalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
enableVerticalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
data: [],
onRegisterApi: onRegisterApi
};
When $ctrl.showDetails is changed, a simple refresh will swap the columns.
$ctrl.showDetails = !$ctrl.showDetails;
$ctrl.itemList.api.grid.refresh();
I hope this is helpful to someone.

Google Linecharts json data source?

I use google line chart but I cant success to assing source to chart.
script
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: '#Url.Action("AylikOkumalar", "Enerji")',
dataType: "json",
async: false
}).responseText;
var rows = new google.visualization.DataTable(jsonData);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'T1');
data.addColumn('number', 'T2');
data.addColumn('number', 'T3');
data.addRows(rows);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div')).draw(data, { curveType: "function",
width: 700, height: 400,
vAxis: { maxValue: 10 }
}
);
}
</script>
action
public ActionResult AylikOkumalar()
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = sayac_okumalari.Select(x => new
{
okuma_tarihi = ((DateTime)x.okuma_tarihi).ToShortDateString(),
T1 = (int)x.toplam_kullanim_T1,
T2 = (int)x.toplam_kullanim_T2,
T3 = (int)x.toplam_kullanim_T3
});
return Json(sonuc, JsonRequestBehavior.AllowGet);
}
json output
and script error:
Argument given to addRows must be either a number or an array.
I use it first time. So I dont know what should I do. How can use charts with mvc 3. there is no example enough.
Thanks.
data.addRows(rows);
'rows' should be an array - something like :
data.addRows([
[new Date(1977,2,28)], 1, 2, 3],
[new Date(1977,2,28)], 1, 2, 3]
]);
or your jsonData could be instead the whole structure :
{
"cols": [
{"id": "", "label": "Date", "type": "date"},
{"id": "", "label": "T1", "type": "number"}
],
"rows": [
{"c":[{"v": "Apr 24th"}, {"v": 56000} ]},
{"c":[{"v": "May 3rd" }, {"v": 68000} ]}
]
}

Add DatePicker range in single column of jqgrid filter

I’ve been able to add a datepicker into the filter toolbar of a jqgrid with the code below. However, I’m wondering if there’s a way to squeeze two datepickers into this single DateCreated column, so as to specify the range (From, To). Any ideas?
function loadGrid() {
$(tableID).jqGrid({
…
colModel: [
…
{ name: 'DateCreated', index: 'DateCreated', width: 125, searchoptions:{dataInit:datePick, att:{title:'Select Date'}} },
…
})
…
}
datePick = function(elem) {
$(elem).datepicker();
}
If you are open to adding in a plugin, I found the range picker from filament group to be very easy to work with. In under an hour, I had the 3 files downloaded and installed into my project, and the range picker working.
link:filament group daterangepicker
Being that I'm using jquery 1.8 in my project, I ended up getting an updated version from
link:Github filament group daterangepicker jquery 1.8
daterangepicker is also able to take all of the options that datepicker supports, so you shouldn't have much trouble converting. Let me know if you have questions and I'll see if I can help.
For reference, the plugin is dual licensed with MIT and GPL. This is the same license structure as jqgrid, so I assume if you are able to use jqgrid, than this plugin should not be a problem.
UPDATE: Adding Code Example
The important part of this code is in the colModel for date. You simply specify a dataInit function for the search options, then add the daterangepicker. Be careful on the capitalization. That got me more than once. The beforeSelectRow is simply some modification I did in order to make my checkboxes along the side behave as a radio button. It is not needed for daterangepicker to work.
$("#myGrid").jqGrid(
{
url:url,
datatype: "json",
colNames:['Version','Date'],
colModel:[
{name:'version', search:true, stype:'text'},
{name:'date', search:true,stype:"text",searchoptions:{dataInit:function(el){
$(el).daterangepicker({dateFormat:'yy/mm/dd'});
}
}}
],
toolbarfilter: true,
sortname: 'version',
sortorder: "desc",
pager: jQuery('#myPager'),
viewrecords: true,
gridview: true,
multiselect: true,
beforeSelectRow: function(rowId)
{
var selectedIds = jQuery('#myGrid').jqGrid().getGridParam("selarrrow");
jQuery("#myGrid").jqGrid().resetSelection();
if(selectedIds)
{
var id = selectedIds[0]
if(id != rowId)
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
else
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
});
I had to do the very same thing, and Joseph's answer above got me 90% of the way there. So, most of the credit is due to him. I had to modify some stuff to get it to work because the filament date range picker allows for single dates (the today option, the specific date option, etc). I also had to add some code to trigger the search after you selected your date. Here's my update...the meat of what I needed to add was in the beginRequest function:
$(document).ready(function() {
var grid = jQuery('#list').jqGrid({
url: '/myajaxurl',
datatype: 'json',
mtype: 'GET',
colNames: ['Reference #', 'CreatedOn', 'Product', 'Model Number', 'Quantity', 'Transaction Type', 'Created By'],
colModel: [
{ name: 'InventoryTransactionLogId', index: 'InventoryTransactionLogId', align: 'center', sortable: true, search: false },
{
name: 'CreatedOn',
search: true,
stype: 'text',
align: 'center',
formatter: 'date',
formatoptions: { newformat: 'm-d-y H:i' },
sortable: true,
searchoptions: {
dataInit: function(el) {
$(el).daterangepicker({ dateFormat: 'yy/mm/dd', onChange: datePick });
}
}
},
{ name: 'ProductName', index: 'ProductName', align: 'center', sortable: true, search: false },
{ name: 'ModelNo', index: 'ModelNo', align: 'center', sortable: true, search: true },
{ name: 'Quantity', index: 'Quantity', align: 'center', sortable: true, search: false },
{ name: 'Description', index: 'Description', align: 'center', sortable: true, search: false },
{ name: 'UserName', index: 'UserName', align: 'center', sortable: true, search: false }
],
loadtext: "Retrieving Inventory Transaction Log...",
rowNum: 50,
rowList: [25, 50, 100],
sortname: 'InventoryTransactionLogId',
sortorder: 'asc',
pager: '#pager',
ignoreCase: true,
viewrecords: true,
height: 450,
autowidth: true,
scrollOffset: 45,
caption: 'Inventory Transaction Log',
emptyrecords: "No records",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
cell: 'cell',
id: 'InventoryTransactionLogId',
userdata: 'userdata'
},
beforeRequest: function () {
var theGrid = jQuery("#list");
var postData = theGrid.jqGrid('getGridParam', 'postData');
if (postData != undefined && postData.filters != undefined) {
postData.filters = jQuery.jgrid.parse(postData.filters);
//Remove if current field exists
postData.filters.rules = jQuery.grep(postData.filters.rules, function(value) {
if (value.field != 'CreatedOn')
return value;
});
// Parse the range picker field into start/end date
var dateRangeString = $('#gs_CreatedOn').val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split(' - ');
if (dateRange.length == 1) {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[0] + ' 23:59:59.999';
} else {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[1] + ' 23:59:59.999';
}
var startDateFilter = { "field": "CreatedOn", "op": "ge", "data": startDate };
var endDateFilter = { "field": "CreatedOn", "op": "le", "data": endDate };
// Add new filters
postData.filters.rules.push(startDateFilter);
postData.filters.rules.push(endDateFilter);
}
} else {
jQuery.extend(postData, {
});
}
if (postData != undefined && postData.filters != undefined) {
postData.filters = JSON.stringify(postData.filters);
postData._search = true;
}
return [true, ''];
}
});
$('.date').datepicker();
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "bw" });
grid.jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });
});
datePick = function() {
var grid = $("#list");
$("#list")[0].triggerToolbar();
$("#list").trigger("reloadGrid", [{ page: 1 }]);
}

Resources