simple json reading into jqgrid - json

I am trying to read following json data into a jqgrid.
var myStr = { "version" : 2,
"query" : "java",
"location" : "suwanee, ga",
"dupefilter" : true,
"highlight" : true,
"radius" : 25,
"start" : 1,
"end" : 10,
"totalResults" : 826,
"pageNumber" : 0,
"results" : [
{
"jobtitle" : "Software Development Team Lead Job",
"company" : "GM",
"city" : "Roswell",
"state" : "GA",
"country" : "US",
"formattedLocation" : "Roswell, GA",
"source" : "General Motors",
"date" : "Tue, 24 Dec 2013 08:21:00 GMT",
"snippet" : "principles, techniques and best practices. - Demonstrated expert knowledge in <b>Java<\/b> and\/or .NET. - Demonstrated expert knowledge in building, debugging and... ",
"url" : "http:\/\/www.indeed.com\/viewjob?jk=778874434418454d&qd=TOIxqcl1xBNMbg2vKTNLcp5QUXHMUbDABF-wK7BxUqwiE8mPbZ2XU9t5kjdQrB6FlsFPgK13DhJYpBc84nTJQYrzCHZtERhjBNeGyZxL6jI&indpubnum=4675158811138546&atk=18cme6tj519rh3c6",
"onmousedown" : "indeed_clk(this, '1050');",
"latitude" : 34.021976,
"longitude" : -84.35714,
"jobkey" : "778874434418454d",
"sponsored" : false,
"expired" : false,
"formattedLocationFull" : "Roswell, GA",
"formattedRelativeTime" : "1 day ago"
}
,
{
"jobtitle" : "Software Systems Engineer (Java\/J2EE)",
"company" : "Universal Business Solutions",
"city" : "Alpharetta",
"state" : "GA",
"country" : "US",
"formattedLocation" : "Alpharetta, GA",
"source" : "Universal Business Solutions",
"date" : "Tue, 17 Dec 2013 18:37:25 GMT",
"snippet" : "years experience with <b>Java<\/b> & J2EE Must be motivated... environment. Experienced with <b>Java<\/b>, J2EE, Oracle, UNIX, SQL, Unix Shell script, <b>Java<\/b> Script, MVC Desired... ",
"url" : "http:\/\/www.indeed.com\/viewjob?jk=7066b95f71004292&qd=TOIxqcl1xBNMbg2vKTNLcp5QUXHMUbDABF-wK7BxUqwiE8mPbZ2XU9t5kjdQrB6FlsFPgK13DhJYpBc84nTJQYrzCHZtERhjBNeGyZxL6jI&indpubnum=4675158811138546&atk=18cme6tj519rh3c6",
"onmousedown" : "indeed_clk(this, '1050');",
"latitude" : 34.074177,
"longitude" : -84.29121,
"jobkey" : "7066b95f71004292",
"sponsored" : false,
"expired" : false,
"formattedLocationFull" : "Alpharetta, GA",
"formattedRelativeTime" : "8 days ago"
}
,
{
"jobtitle" : "Software Engineer",
"company" : "ACI Worldwide",
"city" : "Norcross",
"state" : "GA",
"country" : "US",
"formattedLocation" : "Norcross, GA",
"source" : "ACI Worldwide",
"date" : "Thu, 19 Dec 2013 11:51:00 GMT",
"snippet" : "\u2022 Experienced <b>Java<\/b> engineer for developing commercial... development experience \u2022 2 years of professional <b>Java<\/b> development with 2+ years of J2EE. \u2022 2 years of... ",
"url" : "http:\/\/www.indeed.com\/viewjob?jk=7ac5988d9e5f0990&qd=TOIxqcl1xBNMbg2vKTNLcp5QUXHMUbDABF-wK7BxUqwiE8mPbZ2XU9t5kjdQrB6FlsFPgK13DhJYpBc84nTJQYrzCHZtERhjBNeGyZxL6jI&indpubnum=4675158811138546&atk=18cme6tj519rh3c6",
"onmousedown" : "indeed_clk(this, '1050');",
"latitude" : 33.93956,
"longitude" : -84.20879,
"jobkey" : "7ac5988d9e5f0990",
"sponsored" : false,
"expired" : false,
"formattedLocationFull" : "Norcross, GA",
"formattedRelativeTime" : "6 days ago"
}
]
};
$("#myGrid").jqGrid({
//url: "testData.xml",
dataType:"json",
data : myStr,
jsonReader: {
repeatitems: false,
root: "results"
},
colNames: ["Trending Jobs"],
colModel: [
{ name: "url" }
],
rowNum: 5,
rowList: [5, 10, 20, 100, 10000],
pager: "#pager",
gridview: true,
rownumbers: true,
viewrecords: true,
height: "auto",
loadonce: true
});
I tried to read the data using jsonreader, set the data type as "json" and root as "results".
There are no data populated in jqgrid, Could anybody educate me, what I am missing here ?

The error in your code there are because of small misunderstanding about the meaning of the options jqGrid. If you define a variable like myStr in your code
var myStr = {
"version" : 2,
...
"results" : [
{
...
}
]
};
you don't use JSON. It's just usage of object literals to create new object. Such syntax is the most simple and effective way to create and initialize an object in JavaScript. Only if properties have special characters it's required to enclose property names in " or '. So the same code can be rewritten as
var myStr = {
version : 2,
...
results : [
{
...
}
]
};
So I wanted to stress that the above don't use JSON at all. The correct value of datatype parameter (not dataType) should be "local" instead of "json". The options jsonReader or loadonce will be ignored in the case. The input data should be array of items specified by data option of jqGrid.
So the fixed code should be like the following
$("#myGrid").jqGrid({
datatype: "local",
data: myStr.results,
colNames: ["Trending Jobs"],
colModel: [
{ name: "url" }
],
rowNum: 5,
rowList: [5, 10, 20, 100, 10000],
pager: "#pager",
gridview: true,
rownumbers: true,
viewrecords: true,
height: "auto"
});
(see the demo).
If your real code do load the data from the server it should use url parameter. In the case the options jsonReader or loadonce can be used and the code will be like below
$("#myGrid").jqGrid({
url: "Sri2.json",
datatype: "json",
jsonReader: {
repeatitems: false,
root: "results"
},
loadonce: true,
colNames: ["Trending Jobs"],
colModel: [
{ name: "url" }
],
rowNum: 5,
rowList: [5, 10, 20, 100, 10000],
pager: "#pager",
gridview: true,
rownumbers: true,
viewrecords: true,
height: "auto"
});
(see another demo).
You code have strange properties like onmousedown. If you need to set onmousedown property on some cell you can use cellattr property in colModel. It allows you to set any additional property to <td> element which represent the cell of the grid. For example one more demo uses the following code
function indeed_clk (obj, id) {
alert("onmousedown with id=" + id);
}
$(function () {
var myStr = {
...
"results" : [
{
...
"onmousedown" : "indeed_clk(this, '1050');",
...
}
]
};
$("#myGrid").jqGrid({
datatype: "local",
data: myStr.results,
colNames: ["Trending Jobs"],
colModel: [
{
name: "url",
title: false,
cellattr: function (rowId, cellValue, rawObject) {
if (rawObject.onmousedown) {
return 'onmousedown="' + rawObject.onmousedown + '"';
}
}
}
],
rowNum: 5,
rowList: [5, 10, 20, 100, 10000],
pager: "#pager",
gridview: true,
rownumbers: true,
viewrecords: true,
height: "auto"
});
});
It set onmousedown attribute which calls global function indeed_clk. onmousedown will be set on the cells in the column url using cellattr property.

Related

KendoUI Grid Server Binding Example

I have successfully set up several KendoUI Grids, but I cannot get one using server-side paging to work.
I modified my rest service so I will return a total value (hard coded right now).
I also modified my javascript source. [see below].
Usually I just get a blank screen.
Would be very grateful for any assistance.
Script:
$(document).ready(function(){
// Setup Rest Service
var loc = ( location.href );
var url = loc.substring( 0, loc.lastIndexOf( "/" ) ) + "/xpRest.xsp/test/";
dataSource = new kendo.data.DataSource({
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true, transport : {
read : {
url : url + "READ",
dataType : "json"
},
type : "READ"
},
schema : {
total: "total",
model : {
id : "unid",
fields : {
unid : {
type : "string",
nullable : false
},
tckNbr : {
type : "string",
editable : false
},
tckSts : {
type : "string",
editable : false
}
}
}
}
});
grid = $("#grid-databound-dataItem").kendoGrid({
dataSource : dataSource,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns : [
{field : "tckNbr", title : "Number", type: "string"},
{field : "tckSts", title : "Status", type: "string"}
]
}).data("kendoGrid");
});
JSON feed:
[
{
"total":100,
"data":
[
{
"tckNbr":"3031",
"tckSts":"1 Not Assigned",
"unid":"0014DA9095BF6D638625810700597A36",
"tckReqs":"Bryan S Schmiedeler",
"tckNts":
[
"Bryan DeBaun"
],
"tckBUs":
[
"NAP\/IFI"
],
"tckApps":"GTM",
"tckType":"Issue",
"tckPriority":"Medium"
},
{
"tckNbr":"3031",
"tckSts":"1 Not Assigned",
"unid":"00598976D88226D2862581070059AD25",
"tckReqs":"Bryan S Schmiedeler",
"tckNts":
[
"Bryan DeBaun"
],
"tckBUs":
[
"NAP\/IFI"
],
"tckApps":"GTM",
"tckType":"Issue",
"tckPriority":"Medium"
}
]
}
]
Correct your JSON feed, you need to return object not array:
{
"total": 10,
"data": []
}
After that say what is data and what is total in you schema:
schema : {
total: "total",
data: "data",
.
.
}
Note: if you mock data like in your case (total: 100, data -> size is 2) your paginatio will be created by total parameter not data itself. You will see 5 pages with same data (that is ok).

Kendo Chart Databinding - Local Json Data with schema

I have below json returned data and like to bind in the Kendo Chart
var stockReportingList= {
"StockDetails" : [
{"Total" : 230, "Sold" : 200, "Unsold" : 30, "Month" : "Jan 2016" },
{"Total" : 550, "Sold" : 430, "Unsold" : 220, "Month" : "Feb 2016" },
{"Total" : 200, "Sold" : 100, "Unsold" : 100, "Month" : "Mar 2016" }
]
}
below is my script to plot chart
$("#MarketStockChart").kendoChart({
dataSource : {
data : stockReportingList
},
seriesDefaults : {
type : "column",
stack: true
},
series : [{
field : "Sold"
name : "Sold"
data : stockReportingList
},
{
field : "UnSold"
name : "UnSold"
data : stockReportingList`enter code here`
}],
valueAxis : {
labels : {
format : "{0}",
visible : true,
position : "top"
}
},
categoryAxis :
{
field : "Month"
}
});
The Kendo Chart not displaying properly, Can you please help me to fix this.
I had make lots of corrections in your code to make your charts work.
Below is your modified code:
<script>
var stockReportingList = {
"StockDetails": [{
"Total": 230,
"Sold": 200,
"Unsold": 30,
"Month": "Jan 2016"
}, {
"Total": 550,
"Sold": 430,
"Unsold": 220,
"Month": "Feb 2016"
}, {
"Total": 200,
"Sold": 100,
"Unsold": 100,
"Month": "Mar 2016"
}]
};
$(function() {
$("#MarketStockChart").kendoChart({
dataSource: {
data: stockReportingList.StockDetails
},
seriesDefaults: {
type: "column",
stack: true
},
series: [{
field: "Sold",
name: "Sold"
}, {
field: "Unsold",
name: "Unsold"
}],
valueAxis: {
labels: {
format: "{0}",
visible: true,
position: "top"
}
},
categoryAxis: {
field: "Month"
}
});
});
</script>
Few changes I am mentioning which I had to make:
I passed stockReportingList.StockDetails as dataSource.
Corrected spelling of Unsold in series. It was not matching with your datasource key.
Wrapped whole code in $(function() {...}) to ensure that DOM has
been loaded.
Removed DataSource option from series as it was not required.
Below is live working example for your code:
http://dojo.telerik.com/epOVe

JQuery Grid-SubGrid for Parent-Child relation

I need some idea, about how to implement a subgrid in the following sceaniro.
The following is the json data that I want to display in the JQuery Grid and Subgrid.
Basically I am getting an object called "Contact" that has a collection called "actionSet".
{
"total" : "10",
"page" : "1",
"records" : "78",
"rows" : [ {
"comment" : null,
"givenName" : "Contact A",
"familyName" : "A",
"actionSet" : [ {
"actionID" : 1,
"actionDueDate" : "2012-12-08",
"actionNote" : "Action 1"
}, {
"actionID" : 2,
"actionDueDate" : "2012-12-08",
"actionNote" : "Action 2"
} ]
} ...]
}
I want eache Grid row to display the "Contact" and the subgris associated with the grid should display "actionSet" collection.
When a particular row in the Grid is selected, I do not want to make a server call to get the associated actions, as they are allready present in the "actionSet".
I have got the Grid working, displaying the "Contacts" nicely, but I get confused while implement the subgrid, as how to get the data for it, as its allready available in json.
jq(function() {
jq("#grid").jqGrid({
url:'/smallworks/project/getall.do',
datatype: 'json',
mtype: 'GET',
colNames:['Id', 'First Name', 'Last Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions: {readonly:true,size:10},hidden:true},
{name:'givenName',index:'givenName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}},
{name:'familyName',index:'familyName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}}
],
postData: {
},
rowNum:20,
rowList:[20,40,60],
height: 200,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Contacts",
emptyrecords: "Empty records",
loadonce: false,
loadComplete: function() {
},
Is this achievable?
Do I need to parse JSON data specially for the subgrid?
How can this be achieved?
I suggest that you save information from actionSet in an object which you can easy access later. For example you can use userData parameter and fill the userdata part of JSON data inside of beforeProcessing. The create subgrid you can follow the answer or another one.
The demo demonstrate the implementation approach:
It uses the following code
var mainGridPrefix = "s_";
$("#grid").jqGrid({
url: "Adofo.json",
datatype: "json",
colNames: ["First Name", "Last Name"],
colModel: [
{ name: "givenName" },
{ name: "familyName" }
],
cmTemplate: {width: 100, editable: true, editrules: {required: true},
editoptions: {size: 10}},
rowNum: 20,
rowList: [20, 40, 60],
pager: "#pager",
gridview: true,
caption: "Contacts",
rownumbers: true,
autoencode: true,
height: "100%",
idPrefix: mainGridPrefix,
subGrid: true,
jsonReader: { repeatitems: false },
beforeProcessing: function (data) {
var rows = data.rows, l = rows.length, i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.actionSet) {
subgrids[item.id] = item.actionSet;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ["Due Date", "Note"],
colModel: [
{ name: "actionDueDate", formatter: "date", sorttype: "date" },
{ name: "actionNote" }
],
sortname: "actionDueDate",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: { repeatitems: false, id: "actionID" },
gridview: true,
idPrefix: rowId + "_"
});
}
});
UPDATED: The JSON data used in the demo one can see below. I added id property which is required for jqGrid. I used actionID as the id of the subgrids:
{
"total": "10",
"page": "1",
"records": "78",
"rows": [
{
"id": 10,
"comment": null,
"givenName": "Contact A",
"familyName": "A",
"actionSet": [
{
"actionID": 1,
"actionDueDate": "2012-12-08",
"actionNote": "Action 1"
},
{
"actionID": 2,
"actionDueDate": "2012-12-09",
"actionNote": "Action 2"
}
]
},
{
"id": 20,
"comment": null,
"givenName": "Contact B",
"familyName": "B",
"actionSet": [
{
"actionID": 3,
"actionDueDate": "2012-12-11",
"actionNote": "Action 3"
},
{
"actionID": 4,
"actionDueDate": "2012-12-10",
"actionNote": "Action 4"
}
]
}
]
}

Can't show the json Data in Treepanel in extjs 4

I am working on showing JSON data in EXTJS 4 TreePanel. But my tree is not showing any data . Please let me know where I am wrong. Let me post my codes below:
View Part: it has got the treepanel
xtype: 'treepanel',
title: 'Standard Geographies',
height: 250,
width: 310,
store: 'Data',
border: 1,
displayField: 'name',
useArrows: true,
rootVisible: true,
multiSelect: true,
preventHeader: true,
renderTo: Ext.getBody(),
columns: [{
xtype: 'treecolumn',
text: 'Standard Geographies',
flex: 1,
sortable: false,
//renderer : change,
dataIndex: 'name'
}],
Model Part: Using json data
Ext.define('TA.model.TAModel', {
extend: 'Ext.data.Model',
fields: ['name','typeId'],
//fields: ['abbr','type'],['name','typeId']
proxy: {
type: 'ajax',
url : 'data/StandardGeoTree.json',
actionMethods: {
read: 'POST'
},
reader: {
type: 'json',
root: 'geographyOptions'
},
}
});
Store Part: I hope all is ok in the store part
Ext.define('TA.store.Data', {
//extend: 'Ext.data.Store',
//model: 'TA.model.TAModel',
extend: 'Ext.data.TreeStore',
model: 'TA.model.TAModel',
autoSync: true,
autoLoad: true,
listeners: {
load:function(){
console.log('Schemes Data store loaded');
}
},
proxy: {
type: 'ajax',
//url : 'data/StandardGeoTree.json',
api: {
//read: 'data/StandardGeo.json',
read: 'data/StandardGeoTree.json',
//update: 'data/updateTradeArea.json'
},
reader: {
type: 'json',
root: 'root',
successProperty: 'success',
idProperty : 'typeId'
}
},
root : {
text: 'Root',
id: 'typeId',
expanded : true,
loaded : true,
children: []
}
});
JSON
{
"success": true,
"root" : [
{
"name": "001-USA",
"typeId" : "1",
"children":[
{"name": "USA", "typeId" : "1", "leaf":"true"},
{"name": "State", "typeId" : "2", "leaf":"true"},
{"name": "DMA", "typeId" : "3", "leaf":"true"},
{"name": "CSA", "typeId" : "4", "leaf":"true"},
]
}
]
}
the store configuration for tree component is actually doesn't need to be so complicated. for example simple store declaration below is enough:
var treestore = Ext.create('Ext.data.TreeStore', {
proxy: {
type: 'ajax',
url: 'data/StandardGeoTree.json'
}
});
then in your tree configuration set store: treestore and rootVisible: false
finally, the store expect json respond in this format:
[{
"text": "To Do",
"cls": "folder",
"expanded": true,
"children": [{
"text": "Go jogging",
"leaf": true
},{
"text": "Take a nap",
"leaf": true
},{
"text": "Climb Everest",
"leaf": true
}]
}]
In your JSON, your root property has to be similar to your children. So it's either "root" or "children", but not both. See this question for the full explanation.
So given you stick to:
reader: {
type: 'json',
root: 'root',
successProperty: 'success',
idProperty : 'typeId'
}
Your JSON should look like so:
{
"success": true,
"root" : [
{
"name": "001-USA",
"typeId" : "1",
"root":[
{"name": "USA", "typeId" : "1", "leaf":"true"},
{"name": "State", "typeId" : "2", "leaf":"true"},
{"name": "DMA", "typeId" : "3", "leaf":"true"},
{"name": "CSA", "typeId" : "4", "leaf":"true"},
]
}
]
}
Nothing worked as solution. So I had to write the below code part in my view which solved my problem. I am pasting the code part below:
var treeStore = Ext.StoreManager.lookup('Data');
treeStore.load();
But I want my store to be loaded automatically. Please let me know if you have any solution to automatically load the store.

Filtering a Ext.data.Store by a particular id returns multiple results

I'm trying to filter my list of auditions by show ID but when the show ID is '1' all auditions that have a show Id of '1x' are being returned. Below is my code.
Audition Model:
Ext.regModel("Audition", {
fields: [
{name: "id", type: "integer"},
{name: "show_id", type: "integer"},
{name: "date", type: "string"},
{name: "details", type: "string"}
],
belongsTo: 'Show',
proxy: {
type: 'ajax',
url : 'app/data/auditions.json',
reader: {
type: 'json',
root: 'auditions',
id : 'id'
}
},
});
app.stores.auditions = new Ext.data.Store({
autoLoad: true,
model: 'Audition',
sorters: 'id'
});
Show Model:
app.models.Show = Ext.regModel("app.models.Show", {
fields: [
{name: "id", type: "integer"},
{name: "title", type: "string"},
{name: "description", type: "string"},
{name: "opening_night", type: "string"},
{name: "schedule", type: "string"},
{name: "producer", type: "string"},
{name: "director", type: "string"},
{name: "status", type: "string"},
{name: "poster", type: "string"},
{name: "year", type: "string"}
],
hasMany: [ {model: 'Audition', name: 'auditions'},
{model: 'Role', name: 'roles'} ],
proxy: {
type: 'ajax',
url : 'app/data/shows.json',
reader: {
type: 'json',
root: 'shows',
id : 'id'
}
},
});
app.stores.shows = new Ext.data.Store({
autoLoad: true,
model: "app.models.Show",
sorters: 'title',
getGroupString : function(record) {
return record.get('title')[0];
}
});
Here's a sample of the json data for each model
Auditions:
{
"auditions": [
{
"id" : "1",
"show_id" : "1",
"date" : "March 1, 2011",
"details" : "Details go here."
},
{
"id" : "2",
"show_id" : "2",
"date" : "March 2, 2011",
"details" : "Details go here."
},
{
"id" : "3",
"show_id" : "12",
"date" : "March 3, 2011",
"details" : "Details go here."
}
]
}
Shows:
{
"shows": [
{
"id" : 1,
"title" : "The Diary of Anne Frank",
"status" : "Coming Soon",
"description" : "Show description goes here.",
"opening_night" : "2010-10-08",
"schedule" : "October 8-24, 2010",
"producer" : "Hello World",
"director" : "Hello World",
"year" : "2010",
"poster" : "thediaryofannefrank.jpg"
},
{
"id" : "2",
"title" : "It’s a Wonderful Life",
"status" : "Coming Soon",
"description" : "Show description goes here.",
"opening_night" : "2010-11-26",
"schedule" : "November 26 - December 19, 2010",
"producer" : "Hello World",
"director" : "Hello World",
"year" : "2010",
"poster" : "itsawonderfullife.jpg"
}
]
}
In the view template for each show I filter the data stores for auditions by show_id
app.stores.auditions.filter('show_id', show.id);
this.showAuditionsList = new Ext.List({
itemTpl: '{date}',
store: app.stores.auditions
});
So using the code above, if I'm on the show page for The Diary of Anne Frank and I want to see all auditions for the show - the code will return audition 1 and 3 - even if audition 3 has a show_id of 12.
In my testing I've found that the filter will keep all auditions that have a show_id of both '1' and '1X' (anything that begins with 1). Is there a better way to filter the store or better yet, query the store to return all auditions?
Thanks!
Also have you tried
app.stores.auditions.filter({
property: 'show_id',
value: show.id,
exactMatch: true
});
or
app.stores.auditions.filterBy(function(record, id) {
return store.id = id;
}, this);
Or if you just want to get that specific record;
var record = app.stores.auditions.getAt(app.stores.auditions.findExact('store_id', store.id));
I have found that to pass an object to filter it must instantiate a new filter, as per the below:
store.filter(new Ext.util.Filter({property:"foo", value:"bar", exactMatch:true});