JQGrid and JSON data from Web2py - json

Q1.json is working (index.json). but i cant display in the jqgrid. i think colmodel names is the problem.Is it required that the colModel name is from database field? i want to display in jqgrid is from my select statements and those variables is from different tables. Not only one table but 3 tables.
Q2.Same row should be displayed in jqgrid but from different table. is it possible?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'{{=URL(r=request,f='call',args=['json','index'])}}',
data: "{}",
datatype: 'json',
mtype: 'GET',
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
}
},
colNames:['code','name','max','min','quantity','amount'],
colModel :[
{name:CODE',index:'CODE', width:55},
{name:'Name', index:'Name',width:100},
{name:'MAX(table2.hour)', index:'MAX(hour)',width:100},
{name:'MIN(tabl2.hour)', index:'MIN(hour)',width:100},
{name:'SUM(quantity)', index:'SUM(quantity)',width:180},
{name:'SUM(amount)', index:'SUM(amount)',width:180}
],
hidegrid: false,
scrollOffset:0,
pager: '#pager',
rowNum:100,
shrinkToFit:false,
//rowList:[10,20,30,50],
//sortname: 'id',
//sortorder: 'desc',
viewrecords: false,
width: "100%",
height: "100%",
caption: 'SALES Grid'
});
});
</script>
{"rows": [0, {"table1": {"Name": "dyon"}, "_extra": {"MAX(table2.hour)": "20130514214301484", "MIN(table2.hour)": "20130514052610093", "SUM(table2.quantity)": 2115.854, "SUM(table2.amount)": 90089.15}, "table3": {"CODE": 1800}}]}
NOTE: i want to display the data in one page only.when i run the index.html it contains rows but it is blank and theres a rows contains 0 per cell.When i run the index.json it contains the data i needed. Im newbie to python. thanks!

The first problem is that you use many options of jqGrid which not exist (see the documentation): data, contentType, complete. You remove the options or use some other options which do what you probably tried to do.
The second problem is the usage of properties in JSON input which has dots inside (like SUM(table2.quantity) for example). To be able to read such properties you have to define jsonmap as function. For example
jsonmap: function (obj) {
return obj._extra["SUM(table2.quantity)"];
}
Because the JSON data have 0 as the first element you will have to fix the above code to somthing like
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}
The first demo demonstrate the results:
The best would be to fix your server code to remove the unneeded 0 item from rows array. If you can't do this on the server side you can do this on the client side inside of beforeProcessing callback.
The demo displays
It uses the following JavaScript code
$("#list").jqGrid({
url: "CrazyGirl.json", // need be changed to youth
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (data) {
return JSON.stringify({}); // send empty object (???)
},
colNames: ["code", "name", "max", "min", "quantity", "amount"],
colModel: [
{name: "code", width: 55, jsonmap: "table3.CODE"},
{name: "name", width: 100, jsonmap: "table1.Name"},
{name: "max", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MAX(table2.hour)"]: "";
}},
{name: "min", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MIN(table2.hour)"]: "";
}},
{name: "quantity", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}},
{name: "amount", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.amount)"]: "";
}}
],
jsonReader: { repeatitems: false },
hidegrid: false,
pager: "#pager",
rowNum: 1000,
shrinkToFit: false,
height: "100%",
caption: "SALES Grid"
});

Related

fill the filter values of a column by it's own values in kendo

I have a kendo grid which is filled with some JSON data,
in the filter window in the grid, you can select a condition Type and then fill the condition value text box and then filter the grid based on your selection.
now I have a column that is filled with just four or five different value.
I want to make the condition value field of the filter section to become a drop-down list and instead of writing those values to select them, I want to choose them from the list. ( I mean in the filter section of the grid column, not in the column itself.)
I read an article which was like what I wanted, but it had added those values in the code,
I should notify you that those fields are not the same each time, so I can't write those value in the filter by hard coding.
even something like this one is very similar to what I wanted ( Filter Condition Created For 'City' Field ), but it's using a different source for getting the condition drop-down values, not grid column itself.
in addition, I can't use JSON data, I must use the information from the kendo grid.
thanks in advance.
I found the solution to my problem at last...
after binding the grid to the data source, by setting a loop on the data source of the grid, I take data of one column of the grid and push it to an array, then I set the filter on that column to the array.
<script type="text/javascript">
var arrayName = [];
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "api/products",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
"Id": { type: "number" },
"Name": { type: "string" },
"IsAvailable": { type: "boolean" },
"Price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown);
},
sort: { field: "Id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
productsDataSource.read();
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
dataBound:
function (e) {
var data = $("#report-grid").data("kendoGrid").dataSource._data;
for (i = 0; i < data.length; i++) {
arrayName.push(data[i].Name);
}
},
autoBind: false,
scrollable: false,
pageable: true,
sortable: true,
filterable: { extra: false },
reorderable: true,
columnMenu: true,
columns: [
{ field: "Id", title: "No", width: "130px" },
{ field: "Name", title: "ProductName", filterable: { ui: SystemFilter } },
{
field: "IsAvailable", title: "Available",
template: '<input type="checkbox" #= IsAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "Price", title: "Price", format: "{0:c}" }
]
});
function SystemFilter(element) {
element.kendoDropDownList({
dataSource: arrayName,
optionLabel: "--Select Name--"
})
};
});
One way that I like to do this is to create a list of my values and add that list to ViewData, which then gets passed to the View.
public IEnumerable<ModelName> GetTypes()
{
//Get data from the table you store your values in.
return dbContext.TypesTable.OrderBy(f => f.Name);
}
public ActionResult YourView()
{
IEnumerable<ModelName> types = GetTypes();
ViewData["MyTypes"] = types;
return View();
}
Then in your grid add a ForeignKey column and set it to look at the ViewData you set earlier.
#(Html.Kendo().Grid<ViewModelName>()
.Name("GridName")
.Columns(columns =>
{
columns.ForeignKey(c => c.RecipientType, (System.Collections.IEnumerable)ViewData["MyTypes"], "TypeId", "Name");
})
)
This column will now display the Name of your value for the current records. Then when you go to edit or add a record, this field will display as a dropdown with all of the possible values.

Frontend - Add new use jqGrid?

I use jqGrid add new record, but i can't put data from grid to json string.
When i run, return code:
error Status: 'Unsupported Media Type'. Error code: 415
And my code:
$(document).ready(function () {
jQuery("#jQGridDemo").jqGrid({
url: 'http://192.168.1.59:8080/sunrise/api/v1/warehouse/getById/1',
mtype: "GET",
contentType: "application/json",
datatype: "json",
colNames: ['wareHouseID', 'name' , 'fullname' , 'company', 'address'],
colModel: [
{ name: 'wareHouseID', index: 'wareHouseID', width: 150,editable:false, editoptions:{readonly:true, size:10}, hidden:true},
{ name: 'name', index: 'name', width: 150,editable:true, editoptions:{size:30}},
{ name: 'fullname', index: 'fullname', width: 150,editable:true,editoptions:{size:30}},
{ name: 'company', index: 'company', width: 150,editable:true,editoptions:{size:30}},
{ name: 'address', index: 'address', width: 150,editable:true,editoptions:{size:30}}
],
rowNum: 10,
rowList:[10,20,30],
width: 1290,
sortname: 'wareHouseID',
sortorder:"desc",
height:235,
gridview: true,
viewrecords: true,
caption: "List User Details",
editurl:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
pager: "#jQGridDemoPager",
ajaxRowOptions : {
type :"POST",
contentType :"application/json",
dataType :"json"
},
serializeRowData: function(postData){
return JSON.stringify(postData);
}
});
$("#jQGridDemo").jqGrid('navGrid','#jQGridDemoPager',
{edit:true, add:true, del:false, search:true},
// Edit options
{
type:"PUT",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
closeAfterEdit:true,
reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
},
//Add option
{
type:"POST",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/new",
closeAfterAdd:true,reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
}
);});
Could you help me to find a problem and how to fix it? Tks very much.
There are many unclear parts in your code. Nevertheless I guess that the main problem which you have is the following: you use ajaxRowOptions to set contentType and you use serializeRowData to serialize the data from request as JSON. The problem is: you use form editing, but ajaxRowOptions and serializeRowData will be used only in case of inline editing.
So you should use
ajaxEditOptions: { contentType :"application/json" },
serializeEditData: function (postData) {
return JSON.stringify(postData);
}
You have to remove onclickSubmit which returns JSON.stringify(postData) additionally.
I hope it should solve the problem. If it will not help then you should write first of all which version of jqGrid you use and which fork of jqGrid you use (free jqGrid, Guriddo jqGrid JS or some old jqGrid in version <= 4.7). You should write additionally more information about the server which reruns the error "'Unsupported Media Type'. Error code: 415".

JQgrid not showing data while rows are generating

Jqgrid is not showing JSON data, however rows are generating
Server side code:
public JsonResult Denominations()
{
.
.
int counter = 0;
var jsonData = new
{
total = result.UserObject.Count,
page = 1,
rows = (
from p in result.UserObject
select new
{
id = ++counter,
cell = new string [] {
p.CurrencyID.ToString(),
p.DenominationID.ToString(),
p.DenominationName.ToString(),
p.DenominatorCount.ToString(),
p.Multiplier.ToString(),
p.TenderID.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Data from server side is like this:
{"total":1,"page":1,"rows":[{"id":1,"cell":["1","1","Penny","0","0.0100","1"]}]}
JavaScript code:
$("#denominators").jqGrid({
url: '/Denominations?tenderid=1&currencyid=1',
contentType: "application/json",
datatype: "json",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
repeatitems: false,
cell: 'cell',
id: 'id',
userdata:'userdata'
},
mtype: "GET",
colNames: ["CurrencyID", "DenominationID", "TenderID", "Multiplier", "DenominationName", "DenominatorCount"],
colModel: [
{ name: "currencyid", width: 80, align: "center" },
{ name: "denominationid", width: 90, align: "center" },
{ name: "tenderid", width: 250 },
{ name: "multiplier", width: 250 },
{ name: "denominationname", width: 95 },
{ name: "denominatorcount", width: 95 },
],
height: 'auto',
loadonce: true,
sortname: "DenominationID",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true
});
View:
<table id="denominators" ></table>
View creates the grid with column header however rows are generated but rows did not any data int.
You use wrong jsonReader. To be exactly the property repeatitems: false is false. It means that the format of every item in rows array is
{
"currencyid": "1",
"denominationid": "1",
"tenderid": 1,
"denominationname": "Penny",
"denominatorcount": "0",
"multiplier": "0.0100"
}
You use
{
"id": 1,
"cell": [
"1",
"1",
"Penny",
"0",
"0.0100",
"1"
]
}
instead. So you should remove jsonReader because the format of input data corresponds the default jsonReader, but you need still reorder the columns of the grid or change the order of items which you place in cell array so that it corresponds the order of columns in colModel.
Additional remarks: you use wrong value for total. It should be the number of pages. By the way you use loadonce: true. In the case you can remove "total":1,"page":1 part from the response and just return array of named items. You should just choose the names of columns the same as the names of properties if the items.

URL field not working with flexigrid no response from URL

When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.

JQGrid Posting JSON data on editRow

I would like to post json data to the server (REST API). When I now double click on a row to edit inline, 'serializeRowData' is called and my server receives a json formatted message in the body. But when I click on the little '+' icon in the pager, 'serializeRowData' is not called.
I'm using version:
JQuery 1.5.2
JQGrid 4.4.1
My Grid looks like:
$("#dbgrid").jqGrid({
url: 'rest/config/dbs',
editurl: 'rest/config/db',
datatype: "json",
height: 255,
width: 600,
colNames:['ID', 'Env', 'Hostname', 'Name', 'Port', 'Service Name', 'SID'],
colModel:[
{name:'id',index:'id', width:30, sorttype:'int'},
{name:'env',index:'env', editable:true, width:50},
{name:'hostName',index:'hostName', editable:true, width:200},
{name:'name',index:'name', editable:true, width:200},
{name:'port',index:'port', editable:true, width:30},
{name:'serviceName',index:'name', editable:true, width:30},
{name:'sid',index:'sid', editable:true, width:30}
],
jsonReader: {
repeatitems: false,
id: "id",
},
rowNum:50,
rowTotal: 2000,
rowList : [20,30,50],
loadonce:false,
mtype: "GET",
rownumbers: true,
rownumWidth: 40,
gridview: true,
pager: '#pdbgrid',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption: "Database Servers" ,
ajaxRowOptions : {
type :"POST",
contentType :"application/json; charset=utf-8",
dataType :"json"
},
serializeRowData: function(postdata){
return JSON.stringify(postdata);
}
});
$("#dbgrid").jqGrid('navGrid','#pdbgrid',{edit:true,add:true,del:true}
Am I missing something?
Any help, along with examples, would be hugely appreciated.
Because that doesn't come in inline editing. You can change last line of your code like this.
$("#dbgrid").jqGrid('navGrid','#pdbgrid',{edit:true,add:true,del:true},
{//edit parameters},
{//add parameters
serializeEditData: function (postdata) {}
},
{//delete parameters}
);
Now if you want to serialize edit data then same function you can write in edit parameters also. This function works for both add and edit. For delete, it will be serializeDelData.
I hope it helps you.
If someone has the same problem here a working solution:
...
$("#dbgrid").jqGrid('navGrid','#pdbgrid',
{edit:true,add:true,del:true},
{
//edit parameters
ajaxEditOptions: jsonOptions,
serializeEditData: createJSON,
closeAfterEdit: true
},
{
//add parameters
ajaxEditOptions: jsonOptions,
serializeEditData: createJSON,
closeAfterAdd: true
},
{
//delete parameters
ajaxDelOptions: jsonOptions,
serializeDelData: createJSON
}
);
var jsonOptions = {
type :"POST",
contentType :"application/json; charset=utf-8",
dataType :"json"
};
function createJSON(postdata) {
if (postdata.id === '_empty')
postdata.id = null; // rest api expects int or null
return JSON.stringify(postdata)
}