Kendo UI Grid JSON DataSource not loading data - json

For some reason I seem to be unable to get any more than the following in the Kendo UI Grid:
HTML:
<div id="grid"></div>
<script>
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})
$("#grid").kendoGrid(
{
dataSource: remoteDataSource,
columns: [
{
title: "Title",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
{
title: "Activity Type",
headerAttributes: {
},
attributes: {
"class": "table-cell",
style: "text-align:center"
},
width: 100,
filterable: true
},
{
title: "Specialty",
filterable: true,
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
},
{
title: "Total Credits",
format: "{0}",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
}
],
height: 430,
scrollable: true,
sortable: true,
pageable: true,
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
},
number: {
eq: "Is equal to",
neq: "Is not equal to",
gte: "Greater Than",
lte: "Less Than"
}
}
}
});
</script>
This is the JSON that is returned to it:
[
{"ActivityID":367,"Title":"Non Webinar Test For Calendar","ActivityType":"Other","TotalCredits":2,"Specialty":"[AB] [AE]"},
{"ActivityID":370,"Title":"Stage - Test SI Changes Part II","ActivityType":"Other","TotalCredits":2,"Specialty":"[NE]"},
{"ActivityID":374,"Title":"Webinar Test Event For Calendar","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[FE] [NE] "},
{"ActivityID":401,"Title":"Module #1 Webinar: Learn Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] ",},
{"ActivityID":403,"Title":"Module #3 Webinar: Learn Even More Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] [AE]",}
]
I feel like I'm really close but am missing the last piece. Any help would be GREATLY appreciated as I'm on a deadline.

common troubles are with missing schema attribute !
add it to grid's - datasource, and check if it is set when you make your json.
(when plain array is serialized/to_json, the data array needs a property indicating the shema)
here an example to make it clear:
js: sample grid initialisation / datasource:
$("#grid").kendoGrid({ dataSource: { transport: { read: "/getdata/fromthisurl" }, schema: { data: "data" } } });
when you make / output your json, see if shema information is in the encoded result:
php:
$somedata= get_my_data();
header("Content-type: application/json");
echo "{\"data\":" .json_encode($somedata). "}";
or:
$viewdata['data'] = get_my_data();
header("Content-type: application/json");
echo (json_encode($viewdata));
so the json that is sent to the grid would look like:
{data:
[
{item}
{item}
]
}
instead of just:
[
{item}
{item}
]

Code looks good. I wonder if you change data source creation as below . Change type from POST to GET and see if it works,
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "GET",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})

Try this,
$(document).ready(function () {
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
});
});

You can see what part of code raise an exception in some debug tool (I'd recommend you Chrome's DevTools (just press F12 key in Chrome).
I'm pretty sure the problem is misssing field attribute in your grid's columns array, so Kendo don't know what data from datasource to display in what column of grid.
columns: [
{
field: "Title", // attr name in json data
title: "Title", // Your custom title for column (it may be anything you want)
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
Don't forget to change request type from "POST" to "GET".

What I found when inspecting the JSON coming back from the grid datasource json query was the field names were being JavaScripted -- what was ActivityID in C# became activityID on the wire...

This is unclean, and I discovered it by accident, but what worked for me was returning Json(Json(dataList)) from the controller instead of Json(dataList).

Related

"No Data" when try to bind data from JSON. Data Grid [DevExtreme]

I have a project that use wcf rest angularJS.
I have already create JSON on
localhost:51458/ServiceRequest.svc/GetAllRequest/
The output looked like this
[{"ASSIGNED_TO":"manager","BODY":"asdasd","CATEGORY":"APP","FILE_NAME":"gambar.jpg","ID":18,"REQUESTER":"user","STATUS":"On Progress","SUBCATEGORY":"BUG FIXING","SUBJECT":"asd","TICKET_NUMBER":"APP_20161014_111_18"},{"ASSIGNED_TO":"manager","BODY":"abc","CATEGORY":"IT","FILE_NAME":"App_Form.docx","ID":19,"REQUESTER":"Trainee 02","STATUS":"Assign","SUBCATEGORY":"REQUEST NEW USER","SUBJECT":"test insert lewat browser","TICKET_NUMBER":"IT_20161017_121_19"},{"ASSIGNED_TO":"tes","BODY":"tes","CATEGORY":"tes","FILE_NAME":"tes","ID":20,"REQUESTER":"tes","STATUS":"Assign","SUBCATEGORY":"tes","SUBJECT":"tes","TICKET_NUMBER":"1231"},{"ASSIGNED_TO":"tes","BODY":"tes","CATEGORY":"tes","FILE_NAME":"asd","ID":22,"REQUESTER":"tes","STATUS":"Assign","SUBCATEGORY":"tes","SUBJECT":"tes","TICKET_NUMBER":"123213"},{"ASSIGNED_TO":"dsfbsd","BODY":"sbfd","CATEGORY":"dvsd","FILE_NAME":"sdfbsdf","ID":38,"REQUESTER":"sdfv","STATUS":"Assign","SUBCATEGORY":"dvdv","SUBJECT":"dvdsv","TICKET_NUMBER":"huih"},{"ASSIGNED_TO":"assignto","BODY":"body","CATEGORY":"category","FILE_NAME":"fileName","ID":40,"REQUESTER":"request","STATUS":"Assign","SUBCATEGORY":"subCategory","SUBJECT":"subject","TICKET_NUMBER":"ABC_1234_98"},{"ASSIGNED_TO":"assignto","BODY":"undefined","CATEGORY":"undefined","FILE_NAME":"fileName","ID":45,"REQUESTER":"request","STATUS":"Assign","SUBCATEGORY":"undefined","SUBJECT":"undefined","TICKET_NUMBER":"[object Object]"}]
I want to bind it to Data Grid on DevExtreme. you can see the code on approval.js
$scope.dataGridOptions = {
dataSource: {
store: {
type: "odata",
url: "http://localhost:51458/ServiceRequest.svc/GetAllRequest"
},
select: [
"ID",
"REQUESTER",
"CATEGORY",
"BODY",
"FILE_NAME",
"ASSIGNED_TO"
],
},
columns: [
{
caption: "ID",
dataField: "ID",
}, {
dataField: "REQUESTER",
width: 250
}, {
caption: "Kategori",
dataField: "CATEGORY",
}, {
caption: "Body",
dataField: "BODY",
}, {
caption: "File Name",
dataField: "FILE_NAME",
}, {
caption: "Assigned To",
dataField: "ASSIGNED_TO",
}
]
}
in the html
<div>
<div id="gridContainer" dx-data-grid="dataGridOptions"></div>
</div>
I'm always getting No Data on the Data Grid. Why it cant get data from localhost? can it use JSON? or the data should be ODATA? because when i try to bind the example data from
https://js.devexpress.com/Demos/DevAV/odata/Products
it can work bind odata example
Thanks in advance
You should try it.
$.getJSON("localhost:51458/ServiceRequest.svc/GetAllRequest/", function (data) {
$("#gridContainer").dxDataGrid({
dataSource: data,
// your code....
}).dxDataGrid("instance");

Parse nested json with a proxy in a Sencha Touch 2 store using rootProperty

I have a JSON response that is nested like the following (simplified, but same format):
{
"response":{
"v":"1.0",
"users":[
{
"firstName":"Nicole",
"LastName":"A",
},
{
"firstName":"John",
"LastName":"B",
},
{
"firstName":"Bob",
"LastName":"C",
}
],
}
}
Here is the model:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
name: 'firstName'
},
{
name: 'lastName'
}
]
}
});
I am starting from the sencha architect tutorial for CityBars, so most of the code should be quite basic, and I am just trying to get the users from the json response loaded. Here is the controller:
Ext.define('MyApp.controller.User', {
extend: 'Ext.app.Controller',
launch: function() {
var me = this;
Ext.Viewport.setMasked({ message: 'Loading Attendees...' });
me.getUsers(function (store) {
me.getDataList().setStore(store);
});
},
getUsers: function(callback) {
var store = Ext.data.StoreManager.lookup('UserStore'),
url = 'http://urltogetjsonresponse'
store.getProxy().setUrl(url);
store.load(function() {
callback(store);
});
},
});
Here is the store:
Ext.define('MyApp.store.UserStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.User',
'Ext.data.proxy.JsonP',
'Ext.data.reader.Json'
],
config: {
model: 'MyApp.model.User',
storeId: 'UserStore',
proxy: {
type: 'jsonp',
reader: {
type: 'json',
rootProperty: 'response.user'
}
}
}
});
I tried 'response.user' but it did not work for me. I have already looked all over and know that using rootProperty: 'user' would work, if the users attribute were at the same level as "response" instead of nested under it. I have also tried adding record: 'users' but that did not seem to work either.
If anybody knows if this is doable and has an easy solution to this, that would be great. I don't actually understand how the proxy works, so if anybody can explain a bit about that, it would be helpful too. Thanks.
Taken from Sencha's documentation about the JSON reader :
{
"count": 1,
"ok": true,
"msg": "Users found",
"users": [{
"userId": 123,
"name": "Ed Spencer",
"email": "ed#sencha.com"
}],
"metaData": {
"idProperty": 'userId',
"rootProperty": "users",
"totalProperty": 'count',
"successProperty": 'ok',
"messageProperty": 'msg'
}
}
The rootProperty here is 'users', so you'll need to specify users (which is the name of the array containing your instances of model) and not user .

ExtJS loading nested JSON data in grid

I have a php-script, which returns the following JSON
[
{
"Code":0,
"Message":"No problem"
},
{
"name":"o016561",
"status":1,
"locks":[
{
"ztn":"155320",
"dtn":"20131111",
"idn":"78"
},
{
"ztn":"155320",
"dtn":"20131111",
"idn":"91"
}
]
},
{
"name":"o011111",
"status":1,
"locks":[
{
"ztn":"155320",
"dtn":"20131111",
"idn":"91"
}
]
},
{
"name":"o019999",
"status":0,
"locks":[
]
},
{
"name":"o020000",
"status":0,
"locks":[
]
},
{
"name":"o020001",
"status":0,
"locks":[
]
}
]
Edit:
The grid should look something like this:
I've been able to load name and status into my grid - so far so good. But the more important part is, that I need the nested data in the locks-array being loaded into my grid, but I just can't get my code working. Any help would be appreciated.
I'm using ExtJS 4.2 if that matters.
Edit 2:
I tried
Ext.define("Locks", {
extend: 'Ext.data.Model',
fields: [
'ztn',
'dtn',
'idn'
]
});
Ext.define("ConnectionModel", {
extend: 'Ext.data.Model',
fields: ['name', 'status'],
hasMany: [{
model: 'Locks',
name: 'locks'
}]
});
var store = Ext.create('Ext.data.Store', {
model: "ConnectionModel",
autoLoad: true,
proxy: {
type: 'ajax',
reader: {
type: 'json',
root: 'name'
}
}
});
but it seemed to be wrong in multiple ways...
and it would be awesome if ztn and dtn could be displayed just seperated with a whitespace in the same column
You can add a renderer to the column. In that renderer you can do anything with the record...
Here's a working fiddle:
http://jsfiddle.net/Vandeplas/MWeGa/3/
Ext.create('Ext.grid.Panel', {
title: 'test',
store: store,
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Status',
dataIndex: 'status'
}, {
text: 'idn',
renderer: function (value, metaData, record, rowIdx, colIdx, store, view) {
values = [];
record.locks().each(function(lock){
values.push(lock.get('idn'));
});
return values.join('<br\>');
}
}, {
text: 'ztn + dtn',
renderer: function (value, metaData, record, rowIdx, colIdx, store, view) {
values = [];
record.locks().each(function(lock){
values.push(lock.get('ztn') + ' ' + lock.get('dtn'));
});
return values.join('<br\>');
}
}],
height: 200,
width: 600,
renderTo: Ext.getBody()
});
Note
If you have control over your backend you better change the form of your data more like this:
{
"code": 0,
"message": "No problem",
"success": true,
"data": [
{
"name": "o016561",
"status": 1,
"locks": [
{
"ztn": "155320",
"dtn": "20131111",
"idn": "78"
},
{
"ztn": "155320",
"dtn": "20131111",
"idn": "91"
}
]
},
{
"name": "o011111",
"status": 1,
"locks": [
{
"ztn": "155320",
"dtn": "20131111",
"idn": "91"
}
]
}
]
}
That way you don't mix your control data (success, message, code,...) with your data and the proxy picks it up correctly (it can be a cause of the problems your experiencing). I added a success boolean => Ext picks it up and goes to the failure handler. It helps a lot with your exception handling.
Here is the proxy for it:
proxy: {
type: 'ajax',
api: {
read: ___URL____
},
reader: {
type: 'json',
root: 'data',
messageProperty: 'message'
}
}

Kendo UI Grid with object ID translation

I'm trying to make a grid with KendoUI with external data via JSON (php+mysql engine) from TABLE A and one of columns of these data, get text labels from another TABLE B.
Example, data are: idPermission=1, user_id=1, business_unit_id=1, permission=10
The user_id=1 I want get from another table (Users) their names, 1=John Doe, 2=Martin Brown.
I want to see "John Doe" instead id 1 in the visualization of grid, and "Martin Brown" instead id 2. When inline (or popup) editing of the records I've already reached the target, and I've a select box with the names and not the ids!
Here is my code:
<script>
$(function() {
var crudServiceBaseUrl = "http://localhost/ajax/";
var dataTable = "UsersPermissions";
// This is the datasource of the grid
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "table_action.php?op=R&tbl="+dataTable,
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "table_action.php?op=U&tbl="+dataTable,
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "table_action.php?op=D&tbl="+dataTable,
type: "POST"
},
create: {
url: crudServiceBaseUrl + "table_action.php?op=C&tbl="+dataTable,
type: "POST"
}
},
batch: true,
pageSize: 10,
schema: {
model: {
id: "idPermission",
fields: {
idPermission: { editable: false, nullable: true },
user_id: { validation: { required: true } },
business_unit_id: {},
permission: { validation: { required: true } },
}
}
}
});
// This is the datasource of the user_id column
usersSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "table_action.php?op=R&tbl=Users",
dataType: "json"
}
},
batch: true,
schema: {
model: {
id: "idUser",
fields: {
idUser: {},
email: {},
password: {},
name: {},
last_login: {},
status: {}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
sortable: {
mode: "single",
allowUnsort: false
},
reorderable: true,
resizable: true,
scrollable: false,
toolbar: ["create"],
columns: [
{
field: "user_id",
editor: function (container, options) { // This is where you can set other control types for the field.
$('<input name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: usersSource,
dataValueField: "idUser",
dataTextField: "name",
});
},
title: "ID Utente"
},
{ field: "business_unit_id", title: "Business Unit"},
{ field: "permission", title: "Permission"},
{ command: ["edit", "destroy"], width: "230px"}],
editable: "inline"
});
});
</script>
How I can make the same thing I've done in editing mode, in view mode?
For achieving that you have to first edit the query of the read operation seeing your sample data it must be like this
SELECT a.idPermission, b.name, a.business_unit_id, a.permission
FROM TABLE_A AS a
JOIN TABLE_B(users) AS B ON a.user_id=b.user_id;
json encode the data and send to client
and in your kendo grid change column user_id to name
I know you were asking about the HTML/JavaScript way, but using MVC, this is a good, alternative way to do it:
http://decisivedata.net/kendo-ui-grid-and-entity-framework-code-first-foreign-key-fields/

Ext JS 4 using JSON in proxy reader will not load records

I am trying to use Ext JS 4 and was playing with one of the grid examples and wanted to use JSON rather than XML. No mater how I code the JSON data, I get no records to load.
Here is my code:
Ext.define('Plant', {
extend: 'Ext.data.Model',
fields: [{
name: 'common',
type: 'string'
}, {
name: 'botanical',
type: 'string'
}, {
name: 'light'
}, ]
});
// Create the Data Store.
var store = Ext.create('Ext.data.Store', {
// Destroy the store if the grid is destroyed.
autoDestroy: true,
model: 'Plant',
proxy: {
type: 'ajax',
url: 'plants.json',
reader: {
type: 'json',
root: 'records'
}
},
sorters: [{
property: 'common',
direction: 'ASC'
}]
});
Here is my data:
{
"records": [
{
"common": "Bloodroot",
"botanical": "Sanguinaria canadensis",
"light": "Mostly Shady"
}, {
"common": "test",
"botanical": "I do not know",
"light": "Mostly Shady"
}
]
}
The XML reader works great, but we want to use JSON.
Thanks in advance
Have a look at this thread! You need to check your url path to plants.json, path starts from 'index.html' or some other similar starting point , and not the .js file where store is located. I tested your code and it works fine, also use autoLoad:true in your Ext.data.Store, i dont see your grid code so.. Cheers!