Mapping JSON data in JQGrid - json

I am using jqGrid 3.6.4 and a jquery 1.4.2 . in my sample i am getting following json data format & i want to map these json data into rows of a jqgrid
{
"page": "1",
"total": 1,
"records": "6",
"rows": [
{
"head": {
"student_name": "Mr S. Jack ",
"year": 2007
},
"sub": [
{
"course_description": "Math ",
"date": "22-04-2010",
"number": 1,
"time_of_add": "2:00",
"day": "today"
}
]
}
]
}
my jqgrid code is as follows
jQuery("#"+subgrid_table_id).jqGrid({
url:"http://localhost/stud/beta/web/GetStud.php?sid="+sid,
dtatype: "json",
colNames: ['Stud Name','Year','Date'.'Number'],
colModel: [ {name:'Stud Name',index:'student_name', width:100, jsonmap:"student_name"},
{name:'Year',index:'year', width:100, jsonmap:"year"},
{name:'Date',index:'date', width:100, jsonmap:"date"},
{name:'Number',index:'number', width:100, jsonmap:"number"}
],
height:'100%',
jsonReader: { repeatitems : false, root:"head" },
});
So now the problem is as my data i.e. student_name and year is under "head" , the jqgrid is enable to locate these two fields. at the same time other two column values i.e. Date and Number lies under "sub" and even those columns i am not be able to map it with jqgrid
so kindly help me how to located these attributes in JQGrid.
Thanks

First of all the code posted has some errors like dtatype: "json" instead of datatype: "json". "},});" instead of "}});" at the end of code and colNames: ['Stud Name','Year','Date'.'Number'] instead of colNames: ['Stud Name','Year','Date','Number']. After fixing this clear bugs you need change jsonmap values. This was your main question. The fixed code will be look like following:
jQuery("#"+subgrid_table_id).jqGrid({
...
datatype: 'json',
colNames: ['Stud Name','Year','Date'.'Number'],
colModel: [
{name:'student_name', width:100, jsonmap:"head.student_name"},
{name:'year', width:100, jsonmap:"head.year"},
{name:'date', width:100, jsonmap:"sub.0.date"},
{name:'number', width:100, jsonmap:"sub.0.number"}
],
jsonReader: { repeatitems:false, root:"rows" }
});
You have to fix root to "rows" and use jsonmap in JSON dot notation (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_dot_notation). I use a little strange notation like "sub.0.number" because sub.0.number in JavaScript is the same as sub[0].number. It works now.
I recommend you think one more about the structure of JSON data which you receive. (see my previous comments to you question): Is "sub" element is really an array with always one element or you want to use subgrids? Probably the data should be changed from sub:[{"":"", ...}] to sub:{"":"", ...}? What do you want to use as a rowid? student_name? Then add id: "head.student_name" to the jsonReader definition or add key: true property to the definition of the column student_name. Or you forget to include it in the JSON data?
And the last suggestion. If you open http://trirand.com/blog/jqgrid/jqgrid.html and opens on the left side of tree the branch "Data Mapping" \ "Data optimization" you will see an example where on use only array instead of named elements in JSON. Such data will be have minimum size and can be transferred more quickly from server to client. You data instead have some fields (like "course_description") which you don't use at all. So if you can make any changes in the server code try to optimize the data transfer rate.

Related

dynamic json for datatables

I've been working with datatables and I'm able to load the datatable using getJson with strongly typed classes etc and it works just great. Until I hit one snag.
There are times I want to populate a datatable with data that "I don't know about" but I always know that it will be one row of data - it is simply a json string with dynamic content.
Now with datatables you can simply populate the table with aaData and aaCol by assigning a json string to it but my json string contains a column and data IE:
First_name:bob and so on.
A column - on Datatables would be populated with sTitle:Column1 etc and assigned to aaCol.
Does anyone know of a plug in that parses a json string into aaCol and aaData for use with datatables?
I believe you can solve your problem using this approach:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "scripts/objects.php",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
In the example above the dataTables uses a serverSide processing, the ajax return a object like this:
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"first_name": "Airi",
"last_name": "Satou",
"position": "Accountant",
"office": "Tokyo",
"start_date": "28th Nov 08",
"salary": "$162,700"
}, ...
You can also set the column name using the "name" property inside the specification of each column.
You can the full example in the following link. If you need more assistance I can make a code on my own later today =)
You can check this JsFiddle to understand how to set the columns names

How to load multidimensional / nested json into a store?

So I'm trying to load the data received from a webservice into a sencha touch 2 store.
The data is nested JSON, however it is made to include multiple dataArrays.
I am working with sencha touch 2.3.1, somewhat equal to Ext JS 4.2. I don't have that much experience with sencha yet, but I'm getting there. I decided to go for MVC, so I'd like the answers to be as close to this as possible :).
This is the example JSON I am using:
[
{
"DataCollection": {
"DataArrayOne": [
{
"Name": "John Smith",
"Age": "19"
},
{
"Name": "Bart Smith",
"Age": "16"
}
],
"DataArrayTwo": [
{
"Date": "20110601",
"Product": "Apple",
"Descr": "",
"Remark": ""
},
{
"Date": "20110601",
"Product": "Orange",
"Descr": "",
"Remark": ""
},
{
"Date": "20110601",
"Product": "Pear",
"Descr": "",
"Remark": ""
}
],
"DataArrayThree": [
{
"SomeTotalCost": "400,50",
"IntrestPercentage": "3"
}
]
}
}
]
Through only one call, I get this json. I don't want to cause any unnecessary traffic so I hope to be able to use the data somehow.
I want to be able to use each DataArray on its own.
The data gets sent to the store through its proxy:
Ext.define("MyApp.store.myDataObjects", {
extend: "Ext.data.Store",
config: {
model: "MyApp.model.myDataObject",
proxy: {
reader: {
type: "json",
rootProperty: "DataCollection"
},
type: "ajax",
api: {
read: "https://localhost/Service.svc/json"
},
limitParam: false,
startParam: false,
pageParam: false,
extraParams: {
id: "",
token: "",
filter: ""
},
writer: {
encodeRequest: true,
type: "json"
}
}
}
});
I am a bit stuck with the model here. I tried using mappings which would look like this:
config: {
fields: [ {
name: "IntrestPercentage",
mapping: "Calculation.IntrestPercentage",
type: "string"
}
]}
I tried associations as well but to no avail.
According to google chrome console, it doesn't make any objects containing data. I get only 1 object with all values "null".
My endgoal is to be able to show each dataArray in a separate table. So a table for DataArrayOne, a table for DatarrayTwo... The data itself isn't linked. They are only details that have to be shown on a view.
John Smith isn't related to the apples, as in he didn't buy. The apples are just there as an item to be shown.
The possible solutions I've seen yet not understood due to them being outdated are:
ChildStores: You have a master store that receives the data, and then
you split the data to other stores according to rootProperty. I have
no idea how to do this however and I'm not sure if it will work at
all.
Associations, in case I was doing them wrong. I don't think they
are needed because the data isn't linked to each other but it is part
of "DataCollection" though.
Could someone please post an example on how to deal with this unusual(?) kind of nested json.
Or any other solution which will lead to being able to use the 3 dataArrays at will.
Thanks in advance
The best would be to load the complete data with a separate Ext.Ajax.request and then use store.loadData in the success callback. For example:
var data = Ext.decode(response.responseText);
store1.loadData(data[0].DataCollection.DataArrayOne);
store2.loadData(data[0].DataCollection.DataArrayTwo);
store3.loadData(data[0].DataCollection.DataArrayThree);

JSON format for subgrid

hello can any one tell me the json format for local data containing the subgrid values.
i used following format but subgrid data is not loading into the subgrid table.
var data=[{"Left_ssr_id":CaGM33098,"Mismatches":"6","Gaps":"1","AlignLen":"1119","Identity":"99.37","right_ssr_start":17308507,"Qstart":"33","query":"AB-Contig743","subject":"Ca7","Send":"17305359","Score":"2113","Evalue":"0.0","Left_ssr_end":17293825,"right_ssr_end":17308542,"right_ssr_id":CaGM33099 ,"Sstart":"17304241","Qend":"1150","Left_ssr_start":17293811,subgrid:[{"Right_ssr_start":17308507,"Right_ssr_end":17308542},{"Right_ssr_start":17308506,"Right_ssr_end":17308543}]}]
code used to upload the data . The Grid is getting the data but subgrid showing only the header and the blank rows.
$(document).ready(function(){
$("#blastform").submit(function(){
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
dataType: "json",
error: function() {
$(thistarget).html("<span class='error'>Failed to submit form!</span>");
},
success: function(res) {
var data=res;
$("#datatable").jqGrid({
datatype:"local",
data:data,
colNames:['QueryID','SubjectID', . . . 'Right_nearest_distance'],
colModel:[ {name:'query',index:'query', width:55},
{name:'subject',index:'subject', width:80},
.,
.,
{name:'right_near_dist',index:'right_near_dist', width:50, sortable:false}, ],
rowNum:100,
rowList:[100,200,500],
pager: $('#pager2'),
sortname: 'QueryID',
viewrecords: true,
sortorder: 'desc',
loadonce: true,
altRows: true,
pgbuttons: true,
subGrid : true,
subGridUrl: 'local',
subGridRowExpanded: function(subgrid_id, row_id)
{
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
jQuery("#"+subgrid_table_id).jqGrid({
datatype: "local",
colNames: ['ssr_start','ssr_end'],
colModel: [ {name:"Right_ssr_start",index:"Right_ssr_start",width:80,key:true},
{name:"Right_ssr_end",index:"Right_ssr_end",width:130},
],
rowNum:20,
pager: pager_id,
sortname: 'ssr_start',
sortorder: "asc",
height: '100%' });
jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false}) },
caption: 'Blast Results'
});
$("#datatable").jqGrid('navGrid','#pager2', {position: 'right'});
jQuery("#datatable").jqGrid('navGrid','#blastresults',{edit:false,add:false,del:false});
}
})
return false;
}
);
);
You need to configure the localReader settings
see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#array_data
I don't recommend you to make separate ajax call and to use datatype: "local", data: data. You will have many disadvantages. jqGrid provide datatype: "json" type for the case. One can use additional options like jsonReader and jsonmap to inform jqGrid how to get information about grid data from the server response.
The value for var data which you posted provide wrong data. You use variables CaGM33098 and CaGM33099 which are undefined. If you used cut&pased from the server response, then you generate wrong JSON response on the server. Moreover it's strange that subgrid if the item from data array isn't enclosed in ". Probably the server returns from this.action (??? what is this here???) the following data
[
{
"Left_ssr_id": "CaGM33098",
"Mismatches": "6",
"Gaps": "1",
"AlignLen": "1119",
"Identity": "99.37",
"right_ssr_start": 17308507,
"Qstart": "33",
"query": "AB-Contig743",
"subject": "Ca7",
"Send": "17305359",
"Score": "2113",
"Evalue": "0.0",
"Left_ssr_end": 17293825,
"right_ssr_end": 17308542,
"right_ssr_id": "CaGM33099",
"Sstart": "17304241",
"Qend": "1150",
"Left_ssr_start": 17293811,
"subgrid": [
{
"Right_ssr_start": 17308507,
"Right_ssr_end": 17308542
},
{
"Right_ssr_start": 17308506,
"Right_ssr_end": 17308543
}
]
}
]
The old answer and the answer shows how one can implement displaying nested data as subgrid. Another answer shows how to use userdata to load nested data directly from the server. I recommend you to use the last approach.

JQGrid can not load json data from action

I have problem when loading data from action to jqGrid
My action return JSON data:
{"page":"1","records":"31","rows":["{'id':'1','cell':['1','Cant open destop','Destop','Easy','duongls','huyld','minhnq','Finance ','Open']}","{'id':'2','cell':['2','Cant log to email','Email','Normal','thangtd','minhnq','longnh','Secretary ','Assigned']}","{'id':'3','cell':['3','No internet access Edited ver 2 longnh','Connection','Hard','thangtd','longnh','longnh','Secretary ','Closed']}","{'id':'4','cell':['4','Request password','Account','Normal','dungtq','honglm','longnh','Director','Cancelled']}","{'id':'5','cell':['5','Cant open latop','Laptop','Hard','duongls','huyld','minhnq','Director','Closed']}","{'id':'6','cell':['6','issue 11111111111111','','','dungtq','longnh','','Planning','Open']}","{'id':'7','cell':['7','Issue ku minh heo','','','dungtq','longnh','','Planning','Open']}","{'id':'8','cell':['8','New ticket 12345','','','dungtq','longnh','','Planning','Open']}","{'id':'9','cell':['9','Mail server cannot connect','','','haitct','longnh','','Director','Open']}","{'id':'10','cell':['10','aaaaaaaaaaaa','','','dungtq','longnh','','Planning','Open']}"],"total":"4"}
and in JSP I call jqgrid:
$("#list1").jqGrid({
url: "<%=request.getContextPath()%>/pagingIssue?time='+new Date().getTime()",
colNames:['Id','Name', 'Type','Severity', 'Owner','Register', 'Responsor', 'Department','Status'],
colModel:[
{name:'issId',index:'issId', width:40,sortable:true},
{name:'issName',index:'issName', width:200,sortable:true},
{name:'issType',index:'issType', width:100,sortable:true},
{name:'issSeverity',index:'issSeverity', width:100,sortable:true},
{name:'issOwner',index:'issOwner', width:80,sortable:true},
{name:'issRegister',index:'issRegister', width:100,sortable:true},
{name:'issResponsor',index:'issResponsor', width:100,sortable:true},
{name:'department',index:'department', width:120,sortable:true},
{name:'issStatus',index:'issStatus', width:80,sortable:true}],
rowNum:10,
rowList:[10,15,20],
pager: '#pager1',
sortname: 'issId',
datatype: 'json',
recordpos: 'left',
viewrecords: true,
sortorder: 'desc',
multiselect: true,
caption: 'Issue List' });
});
The grid just show Loading...
Can you help me?
By default, your JSON data should be in the format noted in the jqGrid documentation for JSON Data:
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
Your data is close, but rows contains a string
"rows":["{'id' ... ]}"]
instead of an object:
"rows":[{'id' ... ]}]
Also, you should always use double quotes for strings, and never single-quotes (see the state machine diagrams at json.org for more details). So your JSON should look like this:
"rows":[{"id" ... ]}]

jqgrid subgrids each show all items from the json data

I've been trying to implement a simple subgrid within jqgrid to show line items for an invoice. I finally got the subgrids to populate but each subgrid is showing the same list of line items, which is actually all of the entries in the data set.
I'm not quite sure how to debug this but here are some of my potential ideas-
Is it a problem with the way the json store is (not) responding to the GET queries?
Is it because nowhere I define what field within the subgrid data is the "foriegn key" so to speak.
Do I need the subGridUrl to point to json data with only the appropriate data (not every line item)
Example JSON for line items:
order_id points to the id of the order
{
"total": 1,
"records": 6,
"rows": [
{
"description": "PART X",
"order_id": 2,
"qty": 5,
... more fields ...
"id": 1
},
... more ...
],
page: 1
}
JSON for main grid items:
{
"total": 1,
"records": 2,
"rows": [
{
"order_no": 2,
... more fields ...
"id": 2
},
... more ...
],
page:1
}
Applicable parts of my jqqrid script:
jQuery("#mygrid").jqGrid({
... cosmetic stuff for main grid ...
url: "/my_json_url/",
datatype: "json",
colNames:['Order',...],
colModel:[
{name:'order_no', index:'order_no'},
...
],
jsonReader: {
repeatitems:false,
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "",
id: "id",
subgrid: {root: "rows", cell:"", repeatitems: false}
},
prmNames: {subgridid: "order_id"},
subGrid: true,
subGridUrl: "/json_url/to_line_items/",
subGridModel: [{ name : ['qty','description'],
width: [100,100] }]
})navGrid(some options);
I suppose that the code under the URL "/json_url/to_line_items/" don't use id parameter sent by jqGrid. If the user expand the subgrid the rowid of the row will be used as additional parameter of subGridUrl. By the way I don't understand why you use id values of the grid other as the order_id. Currently the id=1 parameter will be appended to the subGridUrl in case of expanding the row with order_id=10. Is it what you want?