jqGrid returns blank cells - json

Can't seem to get the following jqGrid code to work http://cablegate.politicswiki.ie/stackoverflow.html
<script type="text/javascript">
$(document).ready(function(){
jQuery("#list2").jqGrid({
url:'http://tables.googlelabs.com/api/query?sql=SELECT * FROM 333136 LIMIT 10&jsonCallback=?',
datatype: "json",
colModel:[
{name:'ident',index:'ident',label:'ident', width:55},
{name:'date',index:'date',label:'date', width:90},
{name:'sourceId',index:'sourceId',label:'sourceId', width:100},
{name:'source',index:'source',label:'source', width:80},
{name:'tags',index:'tags',label:'tags', width:200}
],
jsonReader: {
repeatitems: false,
root: function (obj) {
var rows = new Array();
for(var i = 0; i < obj.table.rows.length;i++)
{
var row = new Object();
row.id = obj.table.rows[i][0];
row.cell = obj.table.rows[i];
rows[i] = row;
}
return rows;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.table.rows.length; }
},
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"JSON Example"
});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
});
</script>
Have tried a number of things to get it to work. Nothing seems to do it.

I find the question very interesting. So I modified a little your code and it work now. You can see the results live here.
The corresponding JavaScript code is following
jQuery(document).ready(function() {
jQuery("#list2").jqGrid({
url: 'http://tables.googlelabs.com/api/query?sql=' +
encodeURI('SELECT * FROM 333136 LIMIT 10') + '&jsonCallback=?',
postData: "", // don't send any typical jqGrid parameters
datatype: "json", // or "jsonp"
colModel:[
{name:'ident',index:'ident',key:true,width:60,sorttype:'int'},
{name:'date',index:'date', width:130},
{name:'sourceId',index:'sourceId',width:80,sorttype:'int'},
{name:'source',index:'source',width:150},
{name:'tags',label:'tags',width:350}
],
jsonReader: {
cell: "", // the same as cell: function (obj) { return obj; }
root: "table.rows",
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.table.rows.length; }
},
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
sortorder: "desc",
viewrecords: true,
loadonce: true,
height: "100%",
caption: "How to query Google Fusion Tables"
});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
});

Related

How to get json data after redraw of datatable?

When page load for the first time, I got json object returned from controller. But after deletion of a data it doesn't return json object. I mean, I can access requestTable.ajax.json() after initial load of var requestTable = $('#Request-Table').DataTable({});. But after any event when the table got redrawn, requestTable.ajax.json() gives an error.
My main concern is how to get value of recordsTotal from json object after every event. Can anyone assist me with that?
Routes:
Route::group(['prefix' => '/requests'], function () {
Route::get('/show', [
'uses' => 'InvitationController#show',
'as' => 'requests.show',
]);
Route::delete('/delete/{id}', [
'uses' => 'InvitationController#destroy',
'as' => 'requests.destroy',
]);
});
Controller:
public function show()
{
return Datatables::of(Invitation::query()->whereNull('invitation_token'))->make(true);
}
public function destroy($id)
{
$invitations = Invitation::where('id', $id)->delete();
return Response::json($invitations);
}
DataTable Function:
// Initial Load
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
window.requestTable = $('#Request-Table').dataTable();
window.requestTable.fnDraw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
Don't need to send data from delete you can just refresh your table by ajax.reload() function
below i put your code with modify check it's working or not
// Initial Load
var requestTable ;
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
requestTable.ajax.reload();
},
error: function (data) {
console.log('Error:', data);
}
});
});
above var requestTable so in delete function you can access that and requestTable.ajax.reload(); this function you can use to refresh you table

Prevent datasource reloading on change event of kendo grid

I am working on Kendo Grid, On button click, I call a function to reFetch data from db with new Parameters.
function is here
vm.refereshFigure = function (response) {
vm.gridOptions = {
datasource: new kendo.data.DataSource({
type: "odata",
transport: {
read: function (options) {
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
}
},
schema: {
data: "Data",
total: "Total"
},
change: function (e) {
debugger;
e.preventDefault();
},
pageSize: vm.gridConfigurationJson.PageSize ? vm.gridConfigurationJson.PageSize : 10,
group: vm.JsonGroupingCloumns,
aggregate: vm.aggregatesList,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
filter: !!vm.gridConfigurationJson.Filter
? vm.gridConfigurationJson.Filter.filters
: vm.gridConfigurationJson.Filter,
page: vm.gridConfigurationJson.page,
sort: vm.gridConfigurationJson.sort
}),
dataBound: function (e) {
//if (vm.gridConfigurationJson.PageSize != e.sender.pager.dataSource._pageSize) {
// saveGridConfigration(e);
//}
},
groupable: true,
pageable: {
refresh: true,
pageSizes: [10, 25, 50, 100, 200, "All"],
buttonCount: 5,
},
noRecords: true,
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
resizable: true,
reorderable: true,
columnMenu: true,
columns: vm.columnsList,
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
},
excelExport: function (e) {
try {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (this.columns[cellIndex].type == 'date') {
row.cells[cellIndex].format = "yy-MM-dd hh:mm:ss";
row.cells[cellIndex].value =
kendo.parseDate(row.cells[cellIndex].value, "yyyy-MM-ddTHH:mm:ss");
}
}
}
} catch (e) {
}
var filename = "";
if ($scope.figure.captionView != undefined) {
filename = $scope.figure.captionView;
} else if ($scope.figure.caption != undefined) {
filename = $scope.figure.caption;
}
e.workbook.fileName = filename + ".xlsx";
},
};
$scope.filterChanged(response, undefined, $scope.figure.figureId);
};
It called web api two times. Below is the code in read function which executes two times.
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
After first Call, It goes Change() event, then call read() again.
Can anyone help me what I am doing wrong?

Pagination using kendo grid does not work on page load

In my js. i am loading data using kendoGridOptions. I have mapped the data source which fetches all the records. I have configured pageable = true. However noticed that when page load the pagination option are not available they become available only on when i sort one of the columns. following is the configuration of my grid and data source
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: myGridDataSource,
sortable: true,
scrollable: true,
editable:false,
resizable: true,
reorderable: true,
pageable: true,
columnResize: function (e) {
adjustLastColumn(e, this);
},
columns:
[
{
field: "dealType",
title: $.i18n.prop('buyType.label'),
width: "108px"
},
{
field: "myStatus",
title: $.i18n.prop('myStatus.label'),
width: "105px"
},
{
field: "action",
title: $.i18n.prop('action.label'),
width: "105px"
},
],
pdf:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".pdf",
allPages: true,
},
excel:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".xlsx",
allPages: true,
}
}
and my data source is configured as below
transport: {
read: function (e) {
myapi.rootGet("data/mylist?dealId=" + id, function (response) {
var data;
// console.log(response.data)
if (_.isString(response.data)) {
response.data = JSON.parse(response.data);
data = response.data;
setTimeout(function () {
e.success(data);
}, 10000);
}
else {
e.error("XHR response", response.status, JSON.parse(response.data));
}
});
},
},
schema:
{
model: {
id: "id",
fields: {
dealType: {
type: "string"
},
myStatus: {
type: "string"
},
action: {
type: "string"
},
}
},
parse:function(data)
{
return parseData(data);
}
},
serverSorting: false,
serverFiltering: false,
serverPaging: false
};
appreciate if someone can guide what is missing on pagination that does not work on page load.
Thanks,
Anjana
If you are getting "NaN - NaN of 500 items" like error at left bottom corner in grid, then you should add pageSize in dataSource Property.
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: {
data: myGridDataSource,
pageSize: 50
},
....
....
....
pageable: {
pageSizes: [20, 30, 50, 100],
buttonCount: 5
}
});

JQGrid data not being displayed

I have this code for my jqrid. But the data is not getting displayed in grid. The grids gets generated but no data is being shown in the grid. Also I have applied error control but that gives me no error. The code is as follows:
$(document).ready(function () {
'use strict';
var expHeadVal = "12345:Party;12346:Miscellaneous;12347:Conveyance;12348:Staff Welfare";
var webForm = document.forms[0];
var i = 0;
var mydata = "";
var jsonData = {
"records": "4",
"userData":{
},
"rows":[
{"id":"1", "sdate":"2013-03-22","expHead":"Party","expAmt":"1000","expReason":"Yes","expRemark":"FedEx"},
{"id":"2", "sdate":"2013-03-21","expHead":"Conveyance","expAmt":"200","expReason":"Yes","expRemark":"FedEx"},
{"id":"3", "sdate":"2013-03-20","expHead":"Conveyance","expAmt":"165","expReason":"Yes","expRemark":"FedEx"},
{"id":"4", "sdate":"2013-03-11","expHead":"Staff Welfare","expAmt":"1653","expReason":"Yes","expRemark":"FeEx"}
]
}
// alert (jsonData.rows[3].id);
var $grid = $("#View1"),
initDateWithButton = function (elem) {
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true,
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
icons: {primary: 'ui-icon-calculator'}
}).find('span.ui-button-text').css('padding', '0.1em');
}, 100);
},
numberTemplate = {
formatter: 'number',
align: 'right',
sorttype: 'number',
editable: true,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }},
dateTemplate = {
align: 'center',
sorttype: 'date',
editable: true,
formatter: 'date',
formatoptions: { newformat: 'd-M-Y' },
datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}
},
lastSel;
$grid.jqGrid({
datatype: "local",
data: jsonData,
jsonReader : {
// userdata: "userData",
root: "rows",
repeatitems: false,
// id: "1",
records: "records"
},
// data: jsonData,
colNames: ['Date','Expense Head','Amount', 'Reason','Remarks'],
colModel: [
// {name:'id', index:'id', width:15, editable:false, key: true, hidden: true},
{name:'sdate', index:'sdate', width:200, template: dateTemplate },
{name:'expHead', index:'expHead', width:150, editable:true, sorttype:'number',sortable:true, edittype:"select", editoptions:{value:expHeadVal}},
{name:'expAmt', index:'expAmt', width:100, editable:true, template: numberTemplate, summaryType:'sum' },
{name:'expReason', index:'expReason', width:200, editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}},
{name:'expRemark', index:'expRemark', width:200,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}}],
loadtext: "Loading...",
sortname: ['Col0','Col1'],
pager: '#pView1',
caption: "Expense Table",
gridview: true,
rownumbers: true,
autoencode: true,
ignoreCase: true,
viewrecords: true,
sortorder: 'desc',
height: '100%',
editurl: 'clientArray',
beforeSelectRow: function (rowid) {
if (rowid !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
return true;
},
ondblClickRow: function (rowid, iRow, iCol, e) {
var p = this.p, $this = $(this);
// if the row are still non-selected
if ((p.multiselect && $.inArray(rowid, p.selarrrow) < 0) || rowid !== p.selrow)
{ $this.jqGrid("setSelection", rowid, true); }
$this.jqGrid('editRow', rowid, true, function () {
if (e.target.disabled)
{ e.target.disabled = false; }
$("input, select", e.target).focus();
});
return;
},
loadComplete: function () {
alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$grid.jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
$grid.jqGrid('navGrid', '#pView1', {refreshstate: 'current', edit: false, add: false, del: false});
$grid.jqGrid('inlineNav',"#pView1");
});
Can anybody tell me what is missing here?
Thanks for your help in advance.
Siddhartha
You should change data: jsonData to data: jsonData.rows because you use datatype: "local".
By the way jsonReader option will not used in case of datatype: "local". The format of data in jsonData.rows already corresponds default format of input data for datatype: "local". If you do will need to fill jqGrid having datatype: "local" with another format of data you should use localReader option instead of jsonReader (see the documentation).

jqGrid Form Editing - How to POST Edit row to the sql server

I am using jqGrid in my sharepoint webpart and trying to use Form Editing grid.
I dont know how to post data back to the sql server database for add/update/delete.
I am using WCF service that will accept JSON data from the grid.
WCF Method:
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
bool UpdateProjectDeliverable(string ProjectName, string CriticalItemInfo);
JQGrid - Form Edit:
$('#PrjDeliverablesGrid').jqGrid({
datatype: 'json',
colNames: ['ActivityDescription', 'Type', 'CompletionDate'],
colModel: [
{ name: 'ActivityDescription', index: 'ActivityDescription', width: 200, sortable: false, editable: true, edittype: "textarea", editoptions: { rows: "2", cols: "10" }, formoptions: { rowpos: 1, elmprefix: "(*)" }, editrules: { required: true} },
{ name: 'Type', index: 'Type', width: 90, editable: true, edittype: 'select', editoptions: {
value: function () {
var EditVal = LoadDeliverableTypes();
return EditVal;
}
}, /*editoptions: { value: "H:HandOver; CD:Charter (Draft); CF:Charter (Final); P0:Proto 0; P1:Proto 1; P2:Proto 2; P3:Proto 3" },*/formoptions: { rowpos: 2, elmprefix: " " }
},
{ name: 'CompletionDate', index: 'CompletionDate', width: 90, editable: true, sorttype: 'date', formatter: 'date',
editoptions: { size: 12,
dataInit: function (element) {
$(element).datepicker({ dateFormat: 'mm/dd/yyyy' });
},
defaultValue: function () {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return month + "/" + day + "/" + year;
}
},
formoptions: { rowpos: 3, elmprefix: "(*)", elmsuffix: "mm/dd/yyyy" }, editrules: { required: true }
}
],
rowNum: 10,
pager: '#pagerPrjDeliverables',
sortname: 'id',
sortorder: 'desc',
viewrecords: true,
autowidth: true,
gridview: true,
caption: 'Critical Activities/Deliverables'
});
$('#PrjDeliverablesGrid').jqGrid('navGrid', '#pagerPrjDeliverables',
{ view: true, edit: true, add: true, del: true },
{ edit: true,
afterShowForm: function (eparams) {
$('#PrjDeliverablesGrid').jqGrid('setGridParam', { SelCriticalItem: function () {
var row_id = $('#PrjDeliverablesGrid').jqGrid('getGridParam', 'selrow');
var tempCriticalInfo = new object();
tempCriticalInfo.DeliverableName = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'ActivityDescription');
var DeliverableTypeName = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'Type');
tempCriticalInfo.DeliverableTypeID = GetDeliverableTypeIDFromName(DeliverableTypeName);
tempCriticalInfo.CompletionDate = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'CompletionDate');
return tempCriticalInfo;
}
});
},
// serializeEditData: function (projDeliverableAddEditParams) { //USED ON EDIT
// return JSON.stringify(projDeliverableAddEditParams);
// },
onclickSubmit: function (params, SelCriticalItem) {
var Url = "http://vm0301cch:19511/_layouts/AGCO.PB.SharePointUI/WCFPBUtility/WCFPBUtility.svc";
var SelProjectName = document.getElementById("txtProjectID").value;
var data;
SelDelvProjectName = SelProjectName;
$('#PrjDeliverablesGrid').jqGrid({
params.url = Url + "/UpdateProjectDeliverable",
datatype: 'json',
mtype: 'POST',
editData: { ProjectName: SelDelvProjectName },
ajaxEditOptions: { contentType: 'application/json',
success: function (data) {
alert('Deliverables loaded successfully');
},
error: function (data) {
alert('Deliverables loading failed');
}
}
});
},
jqModal: true,
checkOnUpdate: true,
savekey: [true, 13],
navkeys: [true, 38, 40],
checkOnSubmit: true,
reloadAfterSubmit: false,
recreateForm: true,
closeOnEscape: true,
bottominfo: "Fields marked with (*) are required"
}); // edit options
Please help.