Load and save to grid in extjs from nested json - json

I have a nested json for employee leaves and inside which i have leave history and leave eligibility. i need to populate two grids with the json.i can't read from the json or write to it..Please Help...
My Json is...
{
"EmployeeLeaves": {
"ID": 37,
"LeaveEligibility": [
{
"Availed": 4,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 1,
"LeaveTypeId": 60,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 2,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 3,
"LeaveTypeId": 61,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 10,
"Fullpaydays": 10,
"Halfpaydays": 0,
"ID": 4,
"LeaveTypeId": 62,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 0,
"Fullpaydays": 8,
"Halfpaydays": 0,
"ID": 6,
"LeaveTypeId": 63,
"PersonId": 37,
"YearOfLeave": 2013
}
],
"LeaveHistory": [
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 3,
"FromDate": "3/24/2013 12:00:00 AM",
"FullPayDays": 3,
"HalfPayDays": 0,
"ID": 1,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/26/2013 12:00:00 AM"
},
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 1,
"FromDate": "3/30/2013 12:00:00 AM",
"FullPayDays": 1,
"HalfPayDays": 0,
"ID": 2,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/31/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "",
"ApprovedBy": 0,
"Duration": 2,
"FromDate": "2/13/2013 12:00:00 AM",
"FullPayDays": 2,
"HalfPayDays": 0,
"ID": 4,
"LeaveTypeId": 61,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "blha blah",
"StatusId": 70,
"SubstitutePersonId": 1,
"ToDate": "2/14/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/23/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 5,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/27/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/28/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 6,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/29/2013 12:00:00 AM"
}
],
"PLavailedcount": 2
}
}
My Models and store are as follows....
Ext.define('custom.writer.Json', {
extend: 'Ext.data.writer.Json',
getRecordData: function(record) {
Ext.apply(record.data, record.getAssociatedData());
return record.data;
}
});
Ext.define('AM.store.LeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.leaverequest',
autoLoad:true,
proxy: {
type: 'ajax',
url:'ARSENAWeb/employeeleave.json?id=37',
reader: {
type: 'json',
root: 'EmployeeLeaves'
},
writer:new custom.writer.Json({writeAllFields: true}),
api: {
read: 'ARSENAWeb/employeeleave.json?id=37',
update: 'ARSENAWeb/employeeleave.json?id=37',
create:'ARSENAWeb/employeeleave.json?id=37'
}}
});
Ext.define('AM.model.leaverequest', {
extend: 'Ext.data.Model',
fields: ['ID' ],
idProperty: 'ID',
autoSync:true,
uses: ['AM.model.MLeaveHistory','AM.model.MLeaveStatus'],
hasMany: {model: 'MLeaveHistory',model:'MleaveStatus'},
save: function() {
var me = this;
if (me.persistAssociations) {
me.set( me.getAssociatedData() );
}
me.callParent(arguments);
}
});
Ext.define('AM.model.MLeaveHistory', {
extend: 'Ext.data.Model',
fields: [
{name:'ApprovalDate'},
{name:'ApprovedBy'},
{name:'Duration'},
{name:'FromDate'},
{name:'FullPayDays'},
{name:'HalfPayDays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'LossOfPayDays'},
{name:'PersonId'},
{name:'Remarks'},
{name:'StatusId'},
{name:'SubstitutePersonId'},
{name:'ToDate'}
],
belongsTo: 'AM.model.leaverequest'
});
Ext.define('AM.model.MLeaveStatus', {
extend: 'Ext.data.Model',
fields: [ {name:'Availed'},
{name:'Fullpaydays'},
{name:'Halfpaydays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'PersonId'},
{name:'YearOfLeave'}
],
belongsTo: 'AM.model.leaverequest'
});
My Controller is
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['LType','SleaveHistory','SLeaveStatus',
],
models: [
'LeaveType','MLeaveHistory','MLeaveStatus'
],
views: [
'Leave.LeaveRequest','Leave.LeaveHistoryGrid','Leave.LeaveStatusGrid','Leave.HolidayList'
],
init: function() {
this.control({
'viewport >
'LeaveLeaveRequest button[action=reset]': {
click: this.resetForm
},
'LeaveLeaveRequest button[action=save]': {
click: this.saveForm
},
'leaveleavehistorygrid actioncolumn': {
itemclick: this.cancelLeave
},
'leaveleavehistorygrid': {
itemdblclick: this.editLeave
}
});
},
resetForm: function(button){
button.up('form').getForm().reset();
},
saveForm: function(button){
var form = button.up('form').getForm();
form.getValues(true);
var fromDate =new Date( Ext.getCmp('startdate'));//.getValue();
var endDate = new Date(Ext.getCmp('enddate'));
// var nod=Ext.Date.parseDate(fromDate,'m')
// Date.parseDate( String input, String format ) : Date
// var nod=fromDate+endDate;
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((fromDate.getTime() - endDate.getTime())/(oneDay)));
console.log(diffDays);
if (form.isValid()){
var record = form.getRecord();
var values = form.getValues();
// console.log(values);
if(!record){
var newRecord = new AM.model.leaverequest(values);
this.getLeaveRequestStore().add(newRecord);
}else {
record.set(values);
}}
} ,
cancelLeave: function (view, cell, rowIndex, colIndex, e, record, row) {
Ext.Msg.confirm('Remove Qualification', 'Are you sure?', function (button) {
if (button == 'yes') {
var store = Ext.getStore('LeaveRequest');
var newRecord = new AM.model.leaverequest(row);
console.log(record);
console.log(store);
store.remove(record);
store.sync();
}
}, this);
}
});
My Grids are:
Ext.define('AM.view.Leave.LeaveHistoryGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavehistorygrid',
title: 'Leave History',
store: 'LeaveRequest',
xtype: 'cell-editing',
plugins: [
Ext.create('Ext.grid.plugin.RowEditing', {
startEditByClick: function (){},
onEnterKey: function (){}
})
],
initComponent: function() {
this.cellEditing = new Ext.grid.plugin.CellEditing({
clicksToEdit: 1
});
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
this.columns= [
{header: 'Leave Type', dataIndex: 'LeaveTypeId',flex:1},
{header: 'Start Date', dataIndex: 'FromDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1,editor: {
xtype: 'datefield',
forceSelection : true,
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'End Date', dataIndex: 'ToDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1, editor: {
xtype: 'datefield',
format: 'm/d/y',
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'No of Days', dataIndex: 'Duration',flex:1},
// {header: 'Approval Status', dataIndex: 'leaveapprovalstatus',flex:1},
{header: 'Descriptions', dataIndex: 'Remarks',flex:1},
{header: 'Cancel Leave',flex:1,
xtype: 'actioncolumn',
width:30,
action:'cancel',
sortable: false,
items: [{
handler: function(view, cell, rowIndex, colIndex, e, record, row) {
this.addEvents('itemclick');
this.fireEvent('itemclick',view, cell, rowIndex, colIndex, e, record, row);
},
icon: 'ext-4.1.1a-gpl/ext-4.1.1a/docs/extjs/resources/themes/images/default/grid/page-first-disabled.gif',
tooltip: 'Cancel Leave'
}]
}]
this.callParent(arguments);
}
});
Ext.define('AM.view.Leave.LeaveStatusGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavestatusgrid',
title: 'Leave History',
store: 'LeaveRequest',
initComponent: function() {
this.columns= [
{header: 'Type Of Leave', dataIndex: 'typeofleave',flex:1},
{header: 'Available', dataIndex: 'startdate',flex:1},
{header: 'Availed', dataIndex: 'leaveavailed',flex:1},
{header: 'Balance', dataIndex: 'leavebalance',flex:1}];
this.callParent(arguments);
}
});
my form
Ext.define('AM.view.Leave.LeaveRequest', {
extend: 'Ext.form.Panel',
alias: 'widget.LeaveLeaveRequest',
// requires: [
// 'Ext.ux.form.MultiSelect',
// ],
title: 'Leave Request',
// frame:true,
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [ {
text: 'Reset',
action: 'reset'
}, {
text: 'Save',
action: 'save'
}]
}],
initComponent: function() {
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
// var value,value1;
this.items = [{xtype:'fieldset',
layout:'hbox',
items:[{
xtype:'container',
layout:'anchor',
items:[{
xtype:'textfield',
fieldLabel : 'Type of Leave',
labelWidth:'130px',
allowBlank :false,
afterLabelTextTp1:required
},{
// xtype:'checkbox',
// boxLabel: 'Half Day ',
// name: 'durationofleave',
// inputValue: 'halfday',
// uncheckedValue: 'fullday',
// allowBlank :false,
// afterLabelTextTp1:required
// },{
xtype:'datefield',
//renderer: Ext.util.Format.dateRenderer('m/d/y'),
vtype:'daterange',
fieldLabel : 'From Date',
labelWidth:'130px',
id:'FromDate',
afterLabelTextTpl: required,
name : 'FromDate',
endDateField: 'ToDate',
//minValue: new Date(),
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'datefield',
vtype:'daterange',
renderer: Ext.util.Format.dateRenderer('m/d/y'),
fieldLabel : 'To Date',
id:'ToDate',
startDateField: 'FromDate',
labelWidth:'130px',
// onExpand: function() {
// var field = Ext.getCmp('startdate');
// value: field.getValue();
// value1 = this.getValue();
// console.log(value+value1);},
// minValue: new Date(getCmp('startdate')),//Ext.Date.add(new Date(), Ext.Date.DAY, 7) ,
afterLabelTextTpl: required,
name : 'ToDate',
// change: function() {
// value = this.getValue('startdate')
// //var value = this.getValue('startdate');
// console.log(value);
// //this.picker.setValue(Ext.isDate(value) ? value : new Date());
//},
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'textfield',
fieldLabel : 'Number of days',
labelWidth:'130px',
id: 'textfield-field',
afterLabelTextTpl: required,
name : 'noofdays',
allowBlank :false,
afterLabelTextTp1:required
},
{
// xtype: 'multiselect',
// labelWidth:'130px',
// fieldLabel: 'Reporting Manager(s)',
// name: 'reportingmanager',
// id: 'multiselect-field',
// forceSelection : true,
// allowBlank: false,
// store: 'ReportingManager',
// mode: 'local',
// displayField: 'reportingmanager',
// valueField: 'value',
// ddReorder: true,
// afterLabelTextTp1:required
// },{
xtype:'textfield',
fieldLabel : 'Reason',
labelWidth:'130px',
afterLabelTextTpl: required,
name : 'reason',
allowBlank :false,
afterLabelTextTp1:required
}]
},{xtype:'container',width:'300px'},
{
xtype:'container',
items:[{xtype:'leaveleavestatusgrid',
store: 'LeaveRequest',
height: 200,
width: 500
}]
}]
},{xtype:'fieldset',
title:'Leave History',
items:[{xtype:'leaveleavehistorygrid',
store: 'LeaveRequest',
height: 300,
width: '100%'
}]
}];
this.callParent(arguments);
}
});

My json has a little change where the curly braces has been replaced by square braces
{
"EmployeeLeaves": [
{
"ID": 0,
"LeaveHistory": {
"Duration": 2,
"ApprovedBy": "shyam"
},
"PL": "'I don't care!' said the bear"
}
]
}
My model for the same has been changed to
Ext.define('AM.model.EMPLeaveRequest', {
extend: 'Ext.data.Model',
fields: [{
name: 'ID'
}, {
name: 'Duration',
mapping: 'LeaveHistory.Duration'
}, {
name: 'ApprovedBy',
mapping: 'LeaveHistory.ApprovedBy'
}],
proxy: {
type: 'ajax',
batchActions: false,
url: 'data/employeeleave.json',
autoAppendParams: false,
reader: {
type: 'json',
root: 'EmployeeLeaves',
useSimpleAccessors: false
}
}
});
My store is
Ext.define('AM.store.EMPLeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.EMPLeaveRequest',
autoLoad: true//,
});
There is no need for using associations....But only works for one set of data :(

Related

Vega lite, reduce amount of labels on the x-axis

I need to reduce amount of x-axis labels because now you can see what is going on:
Is it possible to adjust the step on the x-axis? I didn't find it in the documentation. In my case, it automatically counts by 200, I would like to control this.
This is my data:
data = [
{
name: 'Email Invite',
value: 6200,
tooltip: 'Total raised by Email Invite: $6200'
},
{
name: 'Text Invite',
value: 1000,
},
{
name: 'Extra Features',
value: 1800,
},
{
name: 'Snap Store',
value: 2400,
},
{
name: 'Social Media',
value: 4100,
},
]
$schema: 'https://vega.github.io/schema/vega-lite/v5.json',
description: 'bar-chart',
"config": {
"style": {
"cell": {
stroke: "#E2E8F0"
}
}
},
data: {
"values": this.data
},
"mark": {"type": "bar", "cornerRadiusTopLeft": 8, "cornerRadiusTopRight": 8},
encoding: {
x: {
field: 'b',
type: 'quantitative',
axis: {
labels: true,
labelAngle: 0,
labelFontSize: 10,
labelColor: '#94A3B8',
ticks: false,
domain: false,
gridColor: "#E2E8F0",
labelPadding: 10,
},
scale: {
paddingInner: 0.2,
paddingOuter: 0.1
},
sort: { field: 'c' }
},
y: {
field: 'a',
type: 'nominal',
axis: {
labelFontSize: 10,
labelColor: '#94A3B8',
ticks: false,
domain: false,
gridColor: "#E2E8F0",
labelPadding: 16,
labelOffset: 3,
}
},
color: {field: 'c', scale: {range: [`#000`]}, legend: null},
tooltip: {field: 'd', type: 'ordinal'}
},
width: "container",
height: 250
};
Thanks in advance!
This is controlled by tick attributes.
You can set a "tickCount", "tickMinStep" or even the values themselves via "values".
https://vega.github.io/vega-lite/docs/axis.html#ticks

How to display two different chart modal in one

I am creating the chart as you see below:
So I can display the charts separately but I cannot display both of the charts on the same chart line.
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<body>
<canvas id="statisticChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15, 12];
new Chart("statisticChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(25,162,242,1)",
borderColor: "rgba(2, 92, 145, 1)",
data: yValues
}]
},
options: {
legend: { display: false },
scales: {
yAxes: [{ ticks: { min: 6, max: 16 } }],
}
}
});
var barColors = ["#19A2F2"];
Chart("statisticChart", {
type: "bar",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {
legend: { display: false },
title: {
display: true,
text: "World Wine Production 2018"
}
}
});
</script>
</body>
</html>
So could you please have a look? Besides I also care about css, so I would like to display the second chart with the color #19A2F2, thanks in advance.
Chart.js supports mixed charts - which involves just using one Chart instance of course.
All you need to do is take the datasets objects of your two individual charts and put those in an array assigned to the Charts' data.datasets property.
For example:
var xValues = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15, 12];
new Chart("statisticChart", {
type: "bar",
data: {
labels: xValues,
datasets: [{
type: "line",
fill: false,
lineTension: 0,
backgroundColor: "rgba(25,162,242,1)",
borderColor: "rgba(2, 92, 145, 1)",
data: yValues,
fill: false
},
{
type: "bar",
backgroundColor: "#19A2F2",
data: yValues
}
]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 6,
max: 16
}
}],
},
title: {
display: true,
text: "World Wine Production 2018"
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="statisticChart" style="width:100%;max-width:600px"></canvas>

Apex charts in Angular 9

I have some problem using apex charts in angular 9, essentially I'm able to see the chart (line chart) when I mock the data as in the first screenshot, but I can't get data from REST API, I mean the chart disappears.
mocked datas
This is the method containing the chart:
drawGraph(){
this.projectService.getLineChartData(this.getID()).then((data) =>{
for(let i = 0; i<data.resourceListSize; i++){
this.chartOptions = {
series: [
{
name: "data",
data: [28, 29, 33, 36, 32, 32, 33]
},
{
name: "Low - 2013",
data: [12, 11, 14, 18, 17, 13, 13]
}
],
chart: {
height: 350,
type: "line",
dropShadow: {
enabled: true,
color: "#000",
top: 18,
left: 7,
blur: 10,
opacity: 0.2
},
toolbar: {
show: false
}
},
colors: ["#77B6EA", "#545454"],
dataLabels: {
enabled: true
},
stroke: {
curve: "smooth"
},
title: {
text: "Average High & Low Temperature",
align: "left"
},
grid: {
borderColor: "#e7e7e7",
row: {
colors: ["#f3f3f3", "transparent"], // takes an array which will be repeated on columns
opacity: 0.5
}
},
markers: {
size: 1
},
xaxis: {
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
title: {
text: "Month"
}
},
yaxis: {
title: {
text: "Temperature"
},
min: 5,
max: 40
},
legend: {
position: "top",
horizontalAlign: "right",
floating: true,
offsetY: -25,
offsetX: -5
}
};
}
})
}
Any help would be appreciated! Thank you
Step 1,
set the configuration with out data like below(minimum configuration)
this.chartOptions = {
series: [],
chart: {
height: 350,
type: "line"
},
xaxis: {}
}
Step 2:
Data from api response and set to "chartoptions" variable,
this.chartOptions.series=[{
name: "data",
data: [28, 29, 33, 36, 32, 32, 33]
}, {
name: "Low - 2013",
data: [12, 11, 14, 18, 17, 13, 13]
}
];
this.chartOptions.xaxis=
{
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
}

Stacked bar chart from JSON file - seems to be ignoring a value

Pretty new to this stuff, so any help is greatly appreciated. To start off with, here is my JSON file's contents:
[
{
"drg": "NONSPECIFIC CEREBROVASCULAR DISORDERS W MCC",
"approved": 124,
"denied": 38
},
{
"drg": "SEIZURES WO MCC",
"approved": 138,
"denied": 26
},
{
"drg": "CHRONIC OBSTRUCTIVE PULMONARY DISEASE W CC",
"approved": 352,
"denied": 61
},
{
"drg": "CHEST PAIN",
"approved": 246,
"denied": 44
},
{
"drg": "TRANSIENT ISCHEMIA",
"approved": 205,
"denied": 37
},
{
"drg": "OTHER DISORDERS OF NERVOUS SYSTEM W CC",
"approved": 133,
"denied": 23
},
{
"drg": "DIABETES W MCC",
"approved": 151,
"denied": 27
},
{
"drg": "CARDIAC ARRHYTHMIA CONDUCTION DISORDERS W CC",
"approved": 336,
"denied": 55
},
{
"drg": "HYPERTENSION WO MCC",
"approved": 177,
"denied": 29
},
{
"drg": "POISONING TOXIC EFFECTS OF DRUGS WO MCC",
"approved": 144,
"denied": 24
}
]
My stacked bar chart, which worked fine with a CSV file, keeps ignoring the "denied" value. I suspect the issue has something to do with my formatting of the "processed_json.push()" portion of my code. It renders the approved value stacked on top of itself. Here is the script file:
<script>
$(document).ready(function() {
var processed_json = new Array();
$.getJSON('/dashboard-test-data/denied-percentage-2015-chart.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].drg, data[i].approved, data[i].denied]);
}
$('#denied-percentage-2015-chart').highcharts({
chart: {
type: 'bar'
},
credits: {
text: 'Vortext Analytics',
href: 'http://www.vortextanalytics.com'
},
title: {
text: 'Top 10 DRG by Denial Percentage 2015'
},
xAxis: {
type: 'category',
},
navigation: {
menuStyle: {
border: '1px solid #ddd',
boxShadow: 'none',
},
menuItemStyle: {
padding: '5px 1.5rem',
},
menuItemHoverStyle: {
backgroundColor: '#f7f7f9',
color: '#666'
},
buttonOptions: {
height: 40,
width: 46,
symbolX: 23,
symbolY: 22,
x: 10,
y: -15,
symbolSize: 13,
}
},
yAxis: {
min: 0,
title: {
text: 'Total Records'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
},
formatter: function() {
return (this.axis.series[1].yData[this.x] / this.total * 100).toPrecision(2) + '%';
}
}
},
legend: {
align: 'left',
x: 0,
verticalAlign: 'bottom',
y: 22,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false,
reversed: true,
},
tooltip: {
shared: true,
pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: {point.y:,0f} of {point.stackTotal:,0f} <b>({point.percentage:.1f}%)</b><br />',
},
plotOptions: {
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textOutline: 'none',
fontWeight: 'normal',
fontSize: '9px'
}
},
pointWidth: 20,
}
},
series: [{
name: 'approved',
color: '#55B4E4',
data: processed_json,
}, {
name: 'denied',
color: '#005079',
data: processed_json,
}],
});
});
});
</script>
Here is what the end product should produce (screen grab from my csv version):
Correct
And here is what I'm getting from the JSON file: incorrect
Any assistance or guidance is greatly appreciated. Thanks.
Have a look at highchart's stacked bar chart example. For each series, data contains the array of values for that series.
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
In your case, instead of creating the processed_json array of objects, you should create separate arrays containing each series' values.
Change the loop this way:
var xAxis = []
, approvedCount = []
, deniedCount = []
for (i = 0; i < data.length; i++) {
xAxis.push(data[i].drg);
approvedCount.push(data[i].approved);
deniedCount.push(data[i].denied);
Then adapt the chart's instantiation accordingly:
// (...)
xAxis: {
categories: xAxis
},
// (...)
series: [{
name: 'approved',
color: '#55B4E4',
data: approvedCount,
}, {
name: 'denied',
color: '#005079',
data: deniedCount,
}],
// (...)

How do I properly format a JSON object in an external file?

I have used the code available from http://codeblitz.wordpress.com/2009/06/22/jquery-charts/
It uses jqPlot. So I have the following sample code Default.html that works:
<script type="text/javascript">
var jsonObj = { "pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ['Jan 2009', 'Feb 2009', 'Mar 2009', 'Apr 2009', 'May 2009', 'June 2009', 'Jul 2009'] };
$(function () {
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
function CreateBarChartOptions()
{
var optionsObj = {
title: 'Blog Statistics',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: jsonObj.xAxis
}
},
series: [{label:'Page Hits'}, {label: 'RSS Hits'}],
legend: {
show: true,
location: 'nw'
},
seriesDefaults:{
shadow: true,
renderer:$.jqplot.BarRenderer,
rendererOptions:{
barPadding: 8,
barMargin: 10
}
},
highlighter: {
showTooltip: true,
tooltipFade: true
}
};
return optionsObj;
}
</script>
I have copied the code and put it into Default.aspx. The only thing I want to change is to be able to get the data from an external file, so now my code is:
<script type="text/javascript">
var jsonObj;
$.getJSON('example.json', function (response)
{
jsonObj = response;
alert(jsonObj.property);
});
$(function () {
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
function CreateBarChartOptions()
{
var optionsObj = {
title: 'Blog Statistics',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: jsonObj.xAxis
}
},
series: [{ label: 'Page Hits' }, { label: 'RSS Hits'}],
legend: {
show: true,
location: 'nw'
},
seriesDefaults: {
shadow: true,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barPadding: 8,
barMargin: 10
}
},
highlighter: {
showTooltip: true,
tooltipFade: true
}
};
return optionsObj;
}
</script>
But jsonObj is always undefined, I'm presuming my file is not formatted properly. I have tried example.json to contain this:
{"pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ['Jan 2009', 'Feb 2009', 'Mar 2009', 'Apr 2009', 'May 2009', 'June 2009', 'Jul 2009']}
and this:
{"pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ["Jan 2009", "Feb 2009", "Mar 2009", "Apr 2009", "May 2009", "June 2009", "Jul 2009"]}
But to no avail. What am I doing wrong?
Thanks for any assistance,
Julian
You'd probably need to do something like:
$.getJSON('example.json', function (response)
{
var jsonObj = response;
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
The way you have it now your annon function to trigger jqplot will run 'inline', while the ajax loading will still be going on.