ext 7 chart proxy data format - javascript

I try to load json data with direct proxy on a cartesian chart in ext 7 like this:
https://fiddle.sencha.com/#view/editor&fiddle/3bae
In this example I load data from ajax but the return data is the same. (its actually copy pasted from my direct api). I have the same result on my testsystem: I can load hardcoded data but not from proxy.
How do I have to format the data so it populates my chart?

the root property of your JSON must be 'result.data'
the data are object, NOT an Array
For yor custom JSON you can write reader transformer, something like this:
...
...
proxy: {
type: 'ajax',
url: 'test.json',
reader: {
type: 'json',
rootProperty: 'data',
fields: ['month', 'value'], // What is it?
transform: {
fn: function (data) {
return Object.values(data.result.data);
},
scope: this
}
}
},
autoLoad: true
});
Or you can change the backend to generate standard extjs json, sample:
{
"users": [
{
"id": 1,
"name": "Ed Spencer",
"email": "ed#sencha.com"
},
{
"id": 2,
"name": "Abe Elias",
"email": "abe#sencha.com"
}
]
}

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

Populating DataTable column with JSON file but DataTable is empty

$.ajax({
'url': 'http://localhost:8080/Retail-war/webresources/products/allProducts',
'method': 'GET',
'contentType': 'application/json',
'headers': {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}).done( function(data) {
$('#existing-product').DataTable( {
"columnDefs": [
{ "targets": -1, "data": null, "defaultContent": "<button>View More Details!</button>"}
],
"aaData": data,
"columns": [
{ "data": "products.productId"},
{ "data": "products.originalPrice"},
{ "data": "products.currentPrice"},
]
})
This is my format of my JSON file and I would like to populate the DataTable with the 3 columns in products but nothing is showing up in the DataTable and no error is thrown too. How can I populate each columns with the columns in the JSON file under the products object?
{
"products": [
{
"productId": 1,
"originalPrice": 60,
"currentPrice": 50
},
{
"productId": 2,
"originalPrice": 80,
"currentPrice": 70
}
]
}
Instead of accessing your data like this...
// does not work
"data": data,
"columns": [
{ "data": "products.productId"},
{ "data": "products.originalPrice"},
{ "data": "products.currentPrice"}
]
Change the initializer to this:
// works
"data": data.products,
"columns": [
{ "data": "productId"},
{ "data": "originalPrice"},
{ "data": "currentPrice"}
]
DataTable needs the iterable object you will be using to be outside of the columns definitions (where the iteration happens).
These changes work for me (in my stripped-down version of your example).
UPDATE:
As requested, here are some more details to explain the situation:
If you try to use "data": data,, then you are providing a JSON object which has this structure:
{"products": [an array of objects]}
This is used by the columns definitions to iterate over your JSON. But there is nothing to iterate over - there is only the one item - the array.
However, if you first drill down one level in your structure by using "data": data.products, you are passing the following JSON to your the columns definitions:
[{row 1 data}, {row 2 data}, ... {row n data}]
This can be iterated by DataTables, to populate each row in its table.
You can still drill down into each object being iterated, if there are nested objects. In your case there aren't any nested objects - but imagine if your data looked like this (a totally artifical example, by the way):
{
"products": [{
"productId": 1,
"originalPrice": {
"currency": "USD",
"amount": 60
},
"currentPrice": 50
}, {
"productId": 2,
"originalPrice": {
"currency": "USD",
"amount": 80
},
"currentPrice": 70
}]
}
In this case, we can access the data like this:
"data": data2.products,
"columns": [
{ "data" : "productId" },
{ "data" : "originalPrice.amount" },
{ "data" : "currentPrice" }
]
Here we see the use of the dot notation to drill down into the originalPrice object, to grab the number we want to display: originalPrice.amount.
By default DataTables expects the array to be called data. You can change it using the dataSrc property, but only if you are using the built-in DataTables Ajax option, which to be honest is recommended anyway. Define your DataTable like this:
$('#existing-product').DataTable( {
ajax: {
url: "http://localhost:8080/Retail-war/webresources/products/allProducts",
dataSrc: "products",
headers: {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}
});
Alternatively rename your array on the server before you echo it back to "data"

Extjs How to load a JSON folder structure into a tree?

I'm trying to create a Extjs tree with JSON data. The data I want to load into the tree contains a folder structure. But when I trie to load the data into the tree, it doesn't show anything.
I have checked the json code here (JSONLint) on errors but everythin looks fine. Which would say that the problem probably is in the extjs part.
I have no idea how to get it works.
I have created a JSON-object like this:
{
"folders": [
{
"name": "Function",
"id": "workspace://SpacesStore/000-000-000",
"folders": [
{
"name": "Evaluation reports",
"id": "workspace://SpacesStore/00-00-4949-9caf-6655fg"
},
{
"name": "Function Reports",
"id": "workspace://SpacesStore/554gg-563-sd555-872e-0098hhjf"
},
{
"name": "Training(POP)",
"id": "workspace://SpacesStore/4334g-67hj-4357-ba96-4343fhj343"
}
]
},
{
"name": "Application data",
"id": "workspace://SpacesStore/3434gg-a761-48a2-83fa-3434f454hu",
"folders": [
{
"name": "Application letters",
"id": "workspace://SpacesStore/23232ff-c95f-4999-sdsd556-00886ggh7765"
}
]
}
]
}
This is the Extjs part where I want to load the JSON data:
initComponent: function() {
// declare a new store and load tree data
this.store = new Ext.data.TreeStore({
// set params
proxy: {
type: 'ajax',
reader: 'json',
url: 'http://localhost:8080/testApp/rest/folder/1'
}
});
this.items = [{
flex: 1
}];
this.callParent();
}
You didn't tell the reader what property to read from:
reader: {
type: 'json',
rootProperty: 'folders'
}

Howto convert JSON to Array

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

Autocomplete in jQuery 1.4.2 jQuery UI 1.8.3

I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris
I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});
Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().
try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo

Categories

Resources