jqGrid is empty with JSON call - jqgrid

My jqGrid is coming empty with JSON call. Though it is working with datatype='jsonstring' but not with json type. here is my JSON
{
"d": {
"total": 6,
"page": 1,
"records": 6,
"rows": [
{
"id": 1,
"Name": "James",
"EMPID": "0000000056",
"EMPDATE": "",
"JOBTYPE": "REQ",
"DEPTID": "FIN",
"STATUS": "P1"
},
{
"id": 2,
"Name": "James",
"EMPID": "R2",
"EMPDATE": "",
"JOBTYPE": "REQ",
"DEPTID": "FIN",
"STATUS": "P1"
},
{
"id": 3,
"Name": "James",
"EMPID": "V2",
"EMPDATE": "",
"JOBTYPE": "VOU",
"DEPTID": "FIN",
"STATUS": ""
},
{
"id": 4,
"Name": "James",
"EMPID": "V1",
"EMPDATE": "",
"JOBTYPE": "VOU",
"DEPTID": "FIN",
"STATUS": ""
},
{
"id": 5,
"Name": "James",
"EMPID": "009017",
"EMPDATE": "",
"JOBTYPE": "PY",
"DEPTID": "",
"STATUS": "V2"
},
{
"id": 6,
"Name": "James",
"EMPID": "009018",
"EMPDATE": "",
"JOBTYPE": "PY",
"DEPTID": "",
"STATUS": "V1"
}
]
}
}
and my jqGrid call from javascript is
function getgrid()
{
$("#list").jqGrid({
url:'http://10.240.26.41/GetGridFields',
datatype: 'json',
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
//serializeGridData: function (postData) {
// return JSON.stringify(postData);
// },
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colModel: [
{ name: 'id', key: true, width: 60, align: "center", hidden: false },
{ name: 'Name', width: 80, sortable: false, hidden: false },
{ name: 'EMPID', width: 180, sortable: false, hidden: false },
{ name: 'EMPDATE', width: 180, sortable: false, hidden: false },
{ name: 'JOBTYPE', width: 180, sortable: false, hidden: false },
{ name: 'DEPTID', width: 180, sortable: false, hidden: false },
{ name: 'STATUS', width: 180, sortable: false, hidden: false }
],
rowNum: 10,
rowList: [10, 20, 300],
pager: "#pager",
viewrecords: true,
gridview: true,
rownumbers: true,
height: 230,
caption: 'Emp Detail'
})
}
Please let me know where i am wrong here. It is working fine with jsonstring.

How you can see on the demo your jqGrid can read your JSON data. I made in the demo only minimal optimization changes which don't important for your main problem.
So I suppose, that you have either the problem with the usage of full URL (you should use '/GetGridFields' instead of 'http://10.240.26.41/GetGridFields') because you can't get Ajax call to another IP host because of the same origin policy. One other possible reason is that you have wrong 'Content-Type' or some other HTTP header. You can examine the HTTP headers with respect of Fiddler, Firebug or just with Developer Tools of IE or Chrome (see "Network" tab).
In any way I would recommend you to include loadError handler to jqGrid. See the answer for details.

I suggest you validate your json result using jslint since using jsonstring is working could be a format type problem

Related

Access nested property in Kendo Grid

Following is the kendo grid where the nested property has to be accessed:
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
transport: {
read: constants.AppUrls.GetUrls().WebApi + "gprScoreprofiel/GetProfielen/" + e.data.id
},
serverPaging: false,
serverSorting: false,
serverFiltering: false,
sortable: { mode: 'single' },
pageSize: 5,
schema: {
type: "json",
data: "items",
model: {
fields: {
isBerekend: { from: "isBerekend", type: "boolean" },
GPR: { from: "gprGebouwVersieId", type: "string" },
En: { from: "en", type: "number" },
Mi: { from: "mi", type: "number" },
Gz: { from: "gz", type: "number" },
Gb: { from: "gb", type: "number" },
Tk: { from: "tk", type: "number" },
Dpg: { from: "dpg", type: "number" },
VariantNaam: { from: "variant.naam", type: "string" }
}
}
}
},
dataBound: function (e) {
},
reorderable: true,
resizable: true,
sortable: true,
columnMenu: false,
scrollable: true, //http://www.telerik.com/forums/max-height-on-grid
pageable: {
refresh: true,
pageSizes: ["All", 10, 20, 50, 100, 200],
buttonCount: 5,
messages: {
display:
"{0} - {1} van {2} adressen", //{0} is the index of the first record on the page, {1} - index of the last record on the page, {2} is the total amount of records
empty: "Geen adressen",
page: "Page",
of: "of {0}", //{0} is total amount of pages
itemsPerPage: "adressen per pagina",
first: "Ga naar de eerste pagina",
previous: "Ga naar de vorige pagihna",
next: "Ga naar de volgende pagina",
last: "Ga naar de laatste pagina",
refresh: "Herlaad"
}
},
columns:
[
{ field: "isBerekend", title: "Berekend", template: "#= isBerekend ? 'Ja' : 'Nee' #" },
{ field: "GPR", title: "GPR versie" },
{ field: "En", title: "Energie" },
{ field: "Mi", title: "Milieu" },
{ field: "Gz", title: "Gezondheid" },
{ field: "Gb", title: "Gebruik" },
{ field: "Tk", title: "Toekomst" },
{ field: "Dpg", title: "Energie en Milieu" },
{ field: "VariantNaam", title: "Variant Naam" }
]
}).data("kendoGrid");
}
On accessing the api we get the following data:
{
"resultaatgegevens": null,
"items": [
{
"isBerekend": true,
"gprGebouwBerekeningId": 37391,
"gprGebouwVersieId": 10,
"gebruikersdoelId": 1,
"gebruikersdoel": "Celfunctie",
"gebruikstypeId": 9,
"gebruikstype": "Twee onder een kap woning",
"bouwjaarKlasseId": 6,
"gemiddeld": 7.0,
"en": 8.4,
"en1": 8.9,
"en2": 6.6,
"en3": 0.0,
"mi": 6.0,
"mi1": 6.6,
"mi2": 6.2,
"mi3": 5.9,
"gz": 6.9,
"gz1": 5.9,
"gz2": 6.9,
"gz3": 7.5,
"gz4": 7.0,
"gb": 7.5,
"gb1": 6.2,
"gb2": 6.7,
"gb3": 10.0,
"gb4": 6.7,
"tk": 6.2,
"tk1": 6.3,
"tk2": 5.6,
"tk3": 6.6,
"dpg": 0.0,
"dpg1": 0.0,
"bouwjaarKlasse": null,
"gprGebouwVersie": null,
"gprScoreprofielByVastgoedItems": null,
"variant": {
"id": 10,
"naam": "VariantId10",
"omschrijving": "VariantId10",
"gprScoreprofielen": null
}
},
{
"isBerekend": false,
"gprGebouwBerekeningId": 0,
"gprGebouwVersieId": 11,
"gebruikersdoelId": 28,
"gebruikersdoel": "Woonfunctie",
"gebruikstypeId": 3,
"gebruikstype": "portiekwoning 1965 1974",
"bouwjaarKlasseId": 3,
"gemiddeld": 5.2,
"en": 5.9,
"en1": 6.0,
"en2": 5.6,
"en3": null,
"mi": 5.0,
"mi1": 5.4,
"mi2": 4.0,
"mi3": 4.8,
"gz": 4.4,
"gz1": 4.5,
"gz2": 4.2,
"gz3": 4.8,
"gz4": 4.2,
"gb": 5.1,
"gb1": 6.0,
"gb2": 6.0,
"gb3": 3.0,
"gb4": 5.4,
"tk": 5.6,
"tk1": 6.0,
"tk2": 6.0,
"tk3": 4.8,
"dpg": null,
"dpg1": null,
"bouwjaarKlasse": null,
"gprGebouwVersie": null,
"gprScoreprofielByVastgoedItems": null,
"variant": null
}
],
"page": 1,
"pageSize": 1000,
"total": 0,
"hasMore": false
}
The grid doesn't work due to variant.naam
From the docs:
A field configuration cannot contain nested fields' configurations.
So, you have two options:
Change your API to return the nested properties in the same level as the items, e.g.: variantnaam;
Or do it in the Javascript before the widget renders it in schema.parse, something like:
schema: {
data: "items",
parse: function(data) {
if (data && data.items) {
var key = "variant";
data.items.forEach((i) => {
if (i[key]) {
Object.keys(i[key]).forEach((k) => {
i[key + k] = i[key][k];
});
}
});
}
return data;
}
}
Demo

amChart failed to initialize after modal is show

$.ajax({
cache: false,
type: "POST",
url: route,
data: data,
success: function(response){
$('#evolutieProdus').show();
function showEvProd(data){
var chart = AmCharts.makeChart("chart_2",{
"type": "serial",
"theme": "dark",
"dataProvider" : data,
"valueAxes": [ {
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
} ],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "[[date]]: <b>[[bucati]] bucati vandute </b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "bucati"
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "date",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
},
"export": {
"enabled": true
}
});
}
showEvProd(response);
console.log(response);
},
error: function(){
toastr.error('Eroare, ceva nu a functionat corect, reveniti mai tarziu');
}
});
This is my ajax call. I receive the callback with the data but in the graph all I see is an undefined. What is wrong with my code .
P.S. If I hard-coding the dataProvider object it works. But I want to load the graph with the data provided by the server via the ajax response.

jqgrid not work on IE8

my below code not worked on IE 8.
Its a JQGrid (treegrid) to display treegrid format from json server. it worked at firefox.
$(function () {
"use strict";
$("#tree").jqGrid({
url: "http://myJSON-URL/",
datatype: "json",
colNames: ['id', 'Prestations'],
colModel: [
{ name: 'id', width: 100, key: true, hidden: true },
{ name: 'name', width: 785, sortable: false }
],
sortname: 'id',
sortorder: "asc",
hiddengrid: true,
gridview: true,
treeGrid: true,
treeGridModel: "adjacency",
ExpandColumn: 'name',
ExpandColClick: true,
jsonReader: { repeatitems: false, root: function (obj) { return obj; } },
height: "auto"
});
});
I think its AJAX cors problem.
Any idea? thanx.
The json server side responsed these:
json = [
{
"id": "1",
"name": "ECHANGEUR",
"level": "0",
"parent": "null",
"isLeaf": false,
"expanded": false,
"loaded": true
},
{
"id": "1_1",
"name": "Intervention Aller sur Site",
"level": "1",
"parent": "1",
"isLeaf": false,
"expanded": false,
"loaded": true
},
{
"id": "1_1_1",
"name": "Date et heure d'arrivée sur le site",
"level": "2",
"parent": "1_1",
"isLeaf": true,
"expanded": true,
"loaded": true
},
{
"id": "1_1_2",
"name": "Consignation de l'échangeur",
"level": "2",
"parent": "1_1",
"isLeaf": true,
"expanded": true,
"loaded": true
}
];
You have just the problem with the bug specific for jqGrid 4.7.x. You can try tree demos which uses different versions of jqGrid and the same code and JSON which you posted:
demo46, demo47, demo48, demo-free-jqGrid-GitHub.
(The last one uses free jqGrid 4.8 which I published recently, see here and here).
You can verify that the demo which uses jqGrid 4.7 only have the problem in IE8 and both other demos have no problem. You can read more about the bug here or here.

jqGrid with ASP.NET MVC Basics Displaying No Data

I've had about 3 goes at trying to learn the jqGrid. Every time has failed. So this time I tried to start with the basics. All I wanted to do was replicate the json data example at http://trirand.com/blog/jqgrid/jqgrid.html .
My best efforts have resulted in a table with rows and columns by every cell has a non-breaking space in it.
With my code, I only departed from the code in that example in the slightest way to account for the fact that I wasn't getting the data from the same data service. But I was getting the exact same data as I was able to extract the json using fiddler.
The code is:
function getData() {
var obj =
{
"page": "1",
"total": 2,
"records": "13",
"rows": [{
"id": "13",
"cell": ["13",
"2007-10-06",
"Client 3",
"1000.00",
"0.00",
"1000.00",
null]
},
{
"id": "12",
"cell": ["12",
"2007-10-06",
"Client 2",
"700.00",
"140.00",
"840.00",
null]
},
{
"id": "11",
"cell": ["11",
"2007-10-06",
"Client 1",
"600.00",
"120.00",
"720.00",
null]
},
{
"id": "10",
"cell": ["10",
"2007-10-06",
"Client 2",
"100.00",
"20.00",
"120.00",
null]
},
{
"id": "9",
"cell": ["9",
"2007-10-06",
"Client 1",
"200.00",
"40.00",
"240.00",
null]
},
{
"id": "8",
"cell": ["8",
"2007-10-06",
"Client 3",
"200.00",
"0.00",
"200.00",
null]
},
{
"id": "7",
"cell": ["7",
"2007-10-05",
"Client 2",
"120.00",
"12.00",
"134.00",
null]
},
{
"id": "6",
"cell": ["6",
"2007-10-05",
"Client 1",
"50.00",
"10.00",
"60.00",
""]
},
{
"id": "5",
"cell": ["5",
"2007-10-05",
"Client 3",
"100.00",
"0.00",
"100.00",
"no tax at all"]
},
{
"id": "4",
"cell": ["4",
"2007-10-04",
"Client 3",
"150.00",
"0.00",
"150.00",
"no tax"]
}],
"userdata": {
"amount": 3220,
"tax": 342,
"total": 3564,
"name": "Totals:"
}
}
return obj;
}
$(function () {
$("#list2").jqGrid({
data: getData()['rows'],
datatype: "local",
colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
colModel: [
{ name: 'id', index: 'id', width: 55 },
{ name: 'invdate', index: 'invdate', width: 90 },
{ name: 'name', index: 'name asc, invdate', width: 100 },
{ name: 'amount', index: 'amount', width: 80, align: "right" },
{ name: 'tax', index: 'tax', width: 80, align: "right" },
{ name: 'total', index: 'total', width: 80, align: "right" },
{ name: 'note', index: 'note', width: 150, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption: "JSON Example"
});
$("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false });
});
Can anyone please help me break my really bad run with this popular javascript library?
I don't find anything wrong with your grid. There is something wrong with your data. I hope your data need to be checked. Also if you are using local as your datatype your data should like below,
var mydata = [
{ id: "11", invdate: "2007-10-06", name: "Client 1", amount: "600.00"
, tax:"120.00", total:"720.00", note: null },
{ id: "12", invdate: "2007-10-06", name: "Client 2", amount: "700.00",
tax:"140.00", total:"840.00", note: null },
{ id: "13", invdate: "2007-10-06", name: "Client 3", amount: "1000.00",
tax:"0.00", total:"1000.00", note: null }
];
This Demo will give you the good start with jQgrid. I have used your grid definition. Hope this helps.

Load local JSON data in jQgrid without AddJsonRows

I'm using the method addJsonRows to add local data to a jQgrid. As this method disables the sorting I need another solution. One restriction: I can't set the url and fetch the data from the server because the data was passed through another component.
Underneath snippet enlightens the case. The commented line shows the restriction, I replaced it by defining a local variable to have a test case.
<script type="text/javascript" language="javascript">
function loadPackageGrid() {
// Get package grid data from hidden input.
// var data = eval("("+$("#qsmId").find(".qsm-data-packages").first().val()+")");
var data = {
"page": "1",
"records": "2",
"rows": [
{ "id": "83123a", "PackageCode": "83123a" },
{ "id": "83566a", "PackageCode": "83566a" }
]
};
$("#packages")[0].addJSONData(data);
};
$(document).ready(function() {
$("#packages").jqGrid({
colModel: [
{ name: 'PackageCode', index: 'PackageCode', width: "110" },
{ name: 'Name', index: 'Name', width: "300" }
],
pager: $('#packagePager'),
datatype: "local",
rowNum: 10000,
viewrecords: true,
caption: "Packages",
height: 150,
pgbuttons: false,
loadonce: true
});
});
</script>
I wonder how I could do this in an other (better) way to keep the sorting feature.
I tried something with the data option, without result.
I suppose that the same question is interesting for other persons. So +1 from me for the question.
You can solve the problem in at least two ways. The first one you can use datatype: "jsonstring" and datastr: data. In the case you need to add additional parameter jsonReader: { repeatitems: false }.
The second way is to use datatype: "local" and data: data.rows. In the case the localReader will be used to read the data from the data.rows array. The default localReader can read the data.
The corresponding demos are here and here.
I modified a little your data: filled "Name" column and included the third item in the input data.
Now you can use local paging, sorting and filtering/searching of the data. I included a little more code to demonstrate the features. Below you find the code of one from the demos:
$(document).ready(function () {
'use strict';
var data = {
"page": "1",
"records": "3",
"rows": [
{ "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
{ "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
{ "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }
]
},
grid = $("#packages");
grid.jqGrid({
colModel: [
{ name: 'PackageCode', index: 'PackageCode', width: "110" },
{ name: 'Name', index: 'Name', width: "300" }
],
pager: '#packagePager',
datatype: "jsonstring",
datastr: data,
jsonReader: { repeatitems: false },
rowNum: 2,
viewrecords: true,
caption: "Packages",
height: "auto",
ignoreCase: true
});
grid.jqGrid('navGrid', '#packagePager',
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
grid.jqGrid('filterToolbar', { defaultSearch: 'cn', stringResult: true });
});
UPDATED: I decided to add more details about the differences between datatype: "jsonstring" and datatype: "local" scenarios because the old answer be read and voted by many readers.
I suggest to modify the above code a little to show better the differences. The fist code uses datatype: "jsonstring"
$(function () {
"use strict";
var data = [
{ id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
{ id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
{ id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
],
$grid = $("#packages");
$grid.jqGrid({
data: data,
datatype: "local",
colModel: [
{ name: "PackageCode", width: 110 },
{ name: "Name", width: 300 }
],
pager: "#packagePager",
rowNum: 2,
rowList: [1, 2, 10],
viewrecords: true,
rownumbers: true,
caption: "Packages",
height: "auto",
sortname: "Name",
autoencode: true,
gridview: true,
ignoreCase: true,
onSelectRow: function (rowid) {
var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
for (p in rowData) {
if (rowData.hasOwnProperty(p)) {
str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\n";
}
}
alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
}
});
$grid.jqGrid("navGrid", "#packagePager",
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
$grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});
It displays (see the demo)
One can see unsorted items in the same order like input data. The items of input data will be saved in internal parameters data and _index. getLocalRow method used in onSelectRow shows that items of internal data contains only properties of input items which names corresponds to name property of some jqGrid columns. Additionally unneeded _id_ property will be added.
On the other side the next demo which uses datatype: "local" displays sorted data and all properties inclusive complex objects will be still saved in the internal data:
The code used in the last demo is included below:
$(function () {
"use strict";
var data = [
{ id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
{ id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
{ id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
],
$grid = $("#packages");
$grid.jqGrid({
data: data,
datatype: "local",
colModel: [
{ name: "PackageCode", width: 110 },
{ name: "Name", width: 300 }
],
pager: "#packagePager",
rowNum: 2,
rowList: [1, 2, 10],
viewrecords: true,
rownumbers: true,
caption: "Packages",
height: "auto",
sortname: "Name",
autoencode: true,
gridview: true,
ignoreCase: true,
onSelectRow: function (rowid) {
var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
for (p in rowData) {
if (rowData.hasOwnProperty(p)) {
str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\"\n";
}
}
alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
}
});
$grid.jqGrid("navGrid", "#packagePager",
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
$grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});
So I would recommend to use datatype: "local" instead of datatype: "jsonstring". datatype: "jsonstring" could have some advantages only in some very specific scenarios.
Great advice, Oleg.
In my web app, I pre-loaded some JSON data which looked like this:
{
WorkflowRuns:
[
{
WorkflowRunID: 1000,
WorkflowRunName: "First record",
},
{
WorkflowRunID: 1001,
WorkflowRunName: "Second record",
}
],
UserInformation:
{
Forename: "Mike",
Surname: "Gledhill"
}
}
And here's the code I needed to create the jqGrid, just based on the WorkflowRuns part of this JSON:
var JSONstring = '{ WorkflowRuns: [ { WorkflowRunID: 1000, .. etc .. } ]';
$("#tblWorkflowRuns").jqGrid({
datatype: "local",
data: JSONstring.WorkflowRuns,
localReader: {
id: "WorkflowRunID",
repeatitems: false
},
...
});
This was a bit of trial and error though.
For example, jqGrid seemed to ignore datastr: JSONstring for me.
And notice how, with local data, I needed to use localReader, rather than jsonReader, otherwise it wouldn't set the row IDs properly.
Hope this helps.

Resources