Display JSON Data using Alloy UI - javascript

I'm simply tring to parse json data and have it display in a datatable using Alloy UI's framework
YUI().use(
'aui-datatable', 'json-parse',
function(Y) {
var columns = [
{ key: 'ID', sortable: true },
{ key: 'Name', sortable: true }
];
var jsonstring = '{"info":['+
'{"ID":"100", "Name":"Roy"},'+
'{"ID":"200", "Name":"Moss"},'+
'{"ID":"300", "Name":"Jen"}'+
']}';
try {
data = Y.JSON.parse(jsonstring);
}
catch (e) {
alert("Invalid data");
}
new Y.DataTable(
{
columns: columns,
data: data
}
).render("#mySearchResultsContainer");
}
1) How would I map ID and Name to the columns in my datatable?
2) How might this be accomplished using data from an external json file?

Here you go: http://jsfiddle.net/9wd8jqtL/
The main problem was that the data you pass into DataTable needs to be an array: you were passing the object. Passing in data.info provides it with the array you want:
new Y.DataTable(
{
columns: columns,
data: data.info
}
).render("#mySearchResultsContainer");
Also, you need to include the Alloy UI data table script one way or another, I think. I certainly did on the jsfiddle to get it working (also I think there may be issues with newer versions of YUI on jsfiddle too), but that shouldn't be an issue elsewhere.
On getting external data, it depends where it's coming from. But most likely you'll need Y.io or similar to load the data, and have your table building function in the callback for when the data returns.

Related

How to display dynamic server side data retrieved from client side using AJAX method in a Javascript Pie Chart, in a html template (ASP.NET)

I have successfully managed to retrieve data from Client Side (C# Back End) to Server Side (Javascript HTML in aspx) using AJAX. Since the example given by the internet uses a inside a to display data, im unsure how i should display my own data dynamically into the Javascript Pie Chart.
This shows the AJAX method in the aspx form, by using POST method to retrieve data from the C# method "calculateAverageLoginRate"
This is the c# method "calculateAverageLoginRate"
This is the result that is displays in an empty web form
This is the original script for the Pie Chart inside the aspx. Note that the value has been hardcoded.
I want to replace the hardcoded values in the piechart with my own dynamic data retrieved from my c# method "calculateAverageLoginRate". Since im using AJAX, im unfamiliar with how AJAX should be coded such that it is able to take the retrieved data, and input it as a piechart value. Please advice, thank you.
Well you are in the right track. Change your success function to below, declare pieData globally. In your success function you assign the response to the pieData array. Your function only returns a single number - so you can just assign it straight away.
//declare globally
var pieData;
// change success function to this
success: function(response) {
pieData = [
{
value: response, //response is from ajax request
color: "#337AB7" //hardcoded color
},
{ //hardcoded object
value: 50,
color: "#FC8213"
}
];
//instantiate chart
new Chart(document.getElementById("pie").getcontext("2d").Pie(pideData));
}
BUT in the event it returns an array in JSON format, you can iterate it like so:
Json (example):
[
{
value: 'some random value1',
color: "#353AB7"
},
{
value: 'some random value2',
color: "#237AB7"
},
{
value: 'some random value3',
color: "#F37AB7"
},
{
value: 'some random value14,
color: "#137AB7"
}
]
Js:
// declare global array
var pieData = [];
// change success function to this
success: function(response) {
response.forEach(function(el) {
pieData.push({value: el.value, color: el.color})
});
new Chart(document.getElementById("pie").getcontext("2d").Pie(pideData));
}

Setting data into a Kendo DataSource Without Ajax

I have some client-side JSON and want to use to "quickly" experiment with various controls without writing all the REST API calls. All I want to do is point any given Kendo DataSource to the local array of data I already have instead of writing all the extra's...but nothing I do works.
I have tried various online examples...can someone direct me to something that actually works?
EXAMPLE:
This particular example is for their Donut Chart using Angular, but I cant use their data calls because of CORS & I am getting tired of writing a new set of REST calls every time I merely want to experiment with a particular control.
var data = [{ ... }, { ... }]
$scope.screenResolution = new kendo.data.DataSource({
// I dont want this at the moment
//transport: {
// read: {
// url: "http://demos.telerik.com/kendo-ui/content/dataviz/js/screen_resolution.json",
// dataType: "json"
// }
//},
sort: {
field: "order",
dir: "asc"
},
group: {
field: "year"
}
});
Datasource has a data property that you can set to a local array.
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-data

I can't find an elegant way to add a Database Source to a dgrid

For now I have
require([
"dojo/on", "dgrid/OnDemandGrid","dgrid/Tree","dgrid/Editor", "dgrid/Keyboard", "dojo/_base/declare",
"dgrid/data/createHierarchicalStore", "data/projects_data",
"dojo/domReady!"
], function(
on, Grid, Tree, Editor, Keyboard, declare, createHierarchicalStore, hierarchicalCountryData
){
var count = 0; // for incrementing edits from button under 1st grid
function nbspFormatter(value){
// returns " " for blank content, to prevent cell collapsing
return value === undefined || value === "" ? " " : value;
}
var StandardGrid = declare([Grid, Keyboard, Editor, Tree]);
window.grid = new StandardGrid({
collection: createHierarchicalStore({ data: hierarchicalCountryData }, true),
columns: [
{renderExpando: true, label: "Name", field:"variant_name", sortable: false, editor: "text", editOn: "dblclick"},
{label: "Visited", field: "bool", sortable: false, editor: "checkbox"},
{label:"Project", field:"project", sortable: false, editor: "text", editOn: "dblclick"},
{label:"locked", field:"locked", editor: "text", editOn: "dblclick"},
{label:"modified", field:"modified", editor: "text", editOn: "dblclick"},
{label:"summary", field:"summary", editor: "text", editOn: "dblclick"}
]
}, "treeGrid2");
grid.on("dgrid-datachange", function(evt){
console.log("data changed: ", evt.oldValue, " -> ", evt.value);
console.log("cell: ", evt.cell.row.id, evt.cell.column.field);
});
grid.on("dgrid-editor-show", function(evt){
console.log("show editOn editor: ", evt);
});
grid.on("dgrid-editor-hide", function(evt){
console.log("hide editOn editor: ", evt);
});
});
data/projects is a js file containing the data. but how to connect this dGrid now to a MySQL database? Can't find any good information in the docs. I think might be something with JSON rest but not sure about this.
Addition:
I can show the db in an HTML Table. is there a suitable possibilty to populate dGrid from a HTML Table?
I am still missing something. Have connections from
Database -> PHP
but can't get result in a proper JS to load into dStore.
The simplest path forward is to write a service in your server-side language of choice (sounds like PHP in this case) that produces JSON output based on the data in your MySQL database. Depending on the potential size of your data, you can potentially design your data to work with one of two out-of-the-box stores in dstore: Request (and Rest if write operations are also involved), or RequestMemory.
The simpler of the two is RequestMemory, which simply combines the features of the Memory store with an up-front server request (via Request). This store will expect the service to respond with one complete data payload: an array of objects where each object is a record in your database. Something like this:
[
{
"id": 1,
"foo": "bar"
},
{
"id": 2,
"foo": "baz"
}
]
The Rest store expects data in the same format, but also expects the service to handle filtering, sorting, and ranges. Filtering and sorting are represented via query string parameters (e.g. foo=bar&baz=bim in the simplest case for filter, and sort(+foo) or sort(-foo) for sort), while ranges are typically represented via the HTTP Range header (e.g. Range: Items 0-9 for the first 10 items).
Implementing a service for the Rest store is obviously more work, but would be preferable if you're expecting your data source to potentially have thousands of items, since RequestMemory would have no choice but to request all of the items up-front.
With either of these stores, once you have a service that outputs JSON as appropriate, you can create an instance of the store with its target pointing to the service endpoint, then pass it to a grid via the collection property.
If your data is intended to represent a hierarchical structure, it should still be possible to mix dstore/Tree into dstore/RequestMemory or dstore/Request, provided that your hierarchy is represented via parent ID references. By default, Tree filters children via a parent property on each item, and reports mayHaveChildren results by inspecting a hasChildren property on each item.

jqGrid using same dataField for multiple columns

I have a jqGrid which gets its data in JSON format by setting the url parameter.
Is it possible to create multiple columns and let them display the same property of the JSON response?
For example in one column i want to display the data formatted in one way, in another column i want to display the data in another way.
Yes, it's possible. The exact implementation depends from the format which you use in the server response. If you use jsonReader: { repeatitems: false } then one can use jsonmap property in colModel. jqGrid uses jsonmap instead of name during reading of response from the server. So the solution of your problem could be about the following
colModel: [
...
{ name: "mainColumn" },
...
{ name: "duplicate1OfMainColumn", jsonmap: "mainColumn" },
...
{ name: "duplicate2OfMainColumn", jsonmap: "mainColumn" },
...
]
Of case you can define different formatter for every from the columns.
If one have to use datatype: "xml" instead of datatype: "json" then one can use xmlmap instead of jsonmap.

Nested data in ExtJS

I download several entities one ajax-request. Then i add them to stores. I need to commit a changes alike one ajax-request. How properly to do it?
Json structure:
{
entity1: [],
entity2: [],
entyty3: []
}
success: function(responce) {
var data = Ext.decode(response.responseText);
store1.add(data['entity1']);
store2.add(data['entity2']);
store3.add(data['entity3']);
}
Well, you can send it as JSON and that can easily be done as follows:
Ext.Ajax.request({
url: 'YourURL',
jsonData: YourObjectRef, // can be any object / array or JSON string
success: function(response, opts) {
// your code
}
});
And if you want to do it with a store use the type auto for the Modelfield. This type can contain any object.
Check the following references:
ExtJs 4.0.7 Stores
ExtJs 3.4.0 Stores
Kindly check autoSync property to automatically sync the Store with its Proxy after every edit to one of its Records. Defaults to false.
you may use like this. because in extjs4, it's necessary to use the model to create a record
success: function(responce) {
var data = Ext.decode(response.responseText),record;
Ext.each(data,function(entity,index,dataItself){
record = Ext.create('YOURMODEL',entity);
store.add(record);
});
}

Categories