using extjs when json is dynamically passed pie-chart is not drawn - json

I've drawn the pie-chart successfully when i directly pass the data like as shown below
data: [{
'name': 'metric one',
'data': 10
}, {
'name': 'metric two',
'data': 7
}, {
'name': 'metric three',
'data': 5
}, {
'name': 'metric four',
'data': 2
}, {
'name': 'metric five',
'data': 27
}]
});
but when i tried to bring those json datas through ajax i'm not getting the pie-chart.
can anyone please tell me some solution for this.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Ext.chart.series.Pie Example</title>
<link rel="stylesheet" href="http://cdn.sencha.io/try/extjs/4.1.0/resources/css/ext-all-gray.css"/>
<script src="http://cdn.sencha.io/try/extjs/4.1.0/ext-all-debug.js"></script>
<script src="extJS/app.js"></script>
</head>
<body>
<div id="myExample"></div>
</body>
</html>
app.js
Ext.onReady(function() {
Ext.Ajax.request({
url: 'getJsonforPie.action',
dataType : "json",
params: {
},
success: function(response){
getResources = response.responseText;
alert(JSON.stringify(getResources))
}
});
// var store = Ext.create('myStore');
//to load data use store.load()
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: getResources
// [{
// 'name': 'metric one',
// 'data': 10
// }, {
// 'name': 'metric two',
// 'data': 7
// }, {
// 'name': 'metric three',
// 'data': 5
// }, {
// 'name': 'metric four',
// 'data': 2
// }, {
// 'name': 'metric five',
// 'data': 27
// }]
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
// calculate and display percentage on hover
var total = 0;
store.each(function(rec) {
total += rec.get('data');
});
this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '%');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
});
struts.xml
<action name="getJsonforPie" class="commonpackage.DashboardUtilities" method="getJsonforPie"/>
getJsonforPie method
public void getJsonforPie() throws IOException
{
HttpServletResponse response= (HttpServletResponse)
ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
JSONArray zoneAreas = new JSONArray();
for(int i=1;i<5;i++)
{
HashMap map=new HashMap();
map.put("name", "metric "+i);
map.put("data", 10);
zoneAreas.put(map);
}
System.out.println(zoneAreas.toString());
response.getWriter().write(zoneAreas.toString());
}
UPDATE 2 (app.js)
Ext.onReady(function() {
var getResources;
var flag=0;
Ext.Ajax.request({
url: 'getJsonforPie.action',
dataType : "json",
params: {
},
success: function(response){
getResources = response.responseText;
createChart(getResources);
}
});
var createChart = function(resources) {
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: resources
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
var total = 0;
store.each(function(rec) {
total += rec.get('data');
});
this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '%');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
}
});

The getResource variable is visible only inside the success function
Move the code that you are using to create the chart to some function and call it inside the success function, it will be something like this:
var createChart = function(resources) {
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: resources
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{ ....
.....
.....
.....
});
});
}
And then call it inside your success function
success: function(response){
getResources = Ext.decode(response.responseText);
createChart(getResources);
alert(JSON.stringify(getResources));
}

Related

jqplot json_encode data not rendering line graph

I return these 2 string from controller in codeigniter using json_encode for jqplot line grapgh
here i fetch the data
$(document).ready(function(){
$(".stats").click(function(){
var site_id = $(this).attr("id");
$.ajax({
url: site_url+"statistics/fetch_stats_data/"+site_id,
async: false,
type: "POST",
data: "type=article",
dataType: "json",
success: function(data) {
stat_events_plot_graph(data['activity_events'], data['activity_tricks']);
}
})
});
});
plot data structure returned as php string from above ajax
[["10/21/2014 05:50",1]]
plot ticks structure returned as php string from above ajax
[[1,"Today"]]
when i send this data to the plot the graph is not rendered
function stat_events_plot_graph(activity_events_live, activity_tricks_live) {
var plot2 = $.jqplot('events', [activity_events_live], {
title: 'Events',
seriesDefaults: {
rendererOptions: {
smooth: false,
animation: {
show: true
}
}
},
legend: { show: false },
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: { formatString: '%b %#d, %#I %p',angle: -90 }
},
yaxis: {
ticks : activity_tricks_live,
}
},
series: [{ lineWidth: 4,
markerOptions: { style: 'square' }
}],
series: [
{ label: 'Toronto' },
{ label: 'New York' }
],
});
}
how do I convert those 2 strings to work with the line graph ?

Highcharts bargraph from json data in angularJS

I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>

how to bring Symbol-outline in pie chart using extjs

when i runs the index.html i'm getting only a pie chart but with no color description .
can anyone please tell me how bring the color Symbol-outline like as shown below
my code is as given below
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Ext.chart.series.Pie Example</title>
<link rel="stylesheet" href="http://cdn.sencha.io/try/extjs/4.1.0/resources/css/ext-all-gray.css"/>
<script src="http://cdn.sencha.io/try/extjs/4.1.0/ext-all-debug.js"></script>
<script src="app.js"></script>
</head>
<body>
<div id="myExample"></div>
</body>
</html>
app.js
Ext.onReady(function() {
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: [{
'name': 'metric one',
'data': 10
}, {
'name': 'metric two',
'data': 7
}, {
'name': 'metric three',
'data': 5
}, {
'name': 'metric four',
'data': 2
}, {
'name': 'metric five',
'data': 27
}]
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
// calculate and display percentage on hover
var total = 0;
store.each(function(rec) {
total += rec.get('data');
});
this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '%');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
});
You forgot to add legend config
...
height: 350,
legend: {
position: 'right'
},
...
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.Store
UPD:
Ext.define('myStore', {
extend: 'Ext.data.Store',
model: 'myModel',
proxy: {
type: 'ajax',
api: {
read: '/urlhere'
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success',
totalProperty: 'total'
}
}
});
expected data: {data: json array here, success: true/false, total: 123}

Multiple series from JSON Highstock

I have a problem with my HighStock, I need another series from JSON.
My code in get_json.php
include('config.php');
$cp = $_REQUEST["c_prot"];
$r=("SELECT * FROM data WHERE cp='$cp'");
$result=mysql_query($r);
while($row = mysql_fetch_array($result)){
$date= strtotime($row['cas'])*1000; // timestamp
$values=hexdec($row['data']); // series1
$val=hexdec($row['src']); // series2
$array[]=array($date, $values,$val); //output array
}
echo json_encode($array);
JSON output is in correct format: [1364852734000, 557, 2884],....
But problem is, that I didn't find how to add second series from JSON to Highstock code
I would like to display in chart x-axis: timestamp
y-axis: series1->data
series2->src
chart now displays only on x-axis timestamp and on y-axis data...but series2 doesn't work:/
High Stock code:
<script>
$(function () {
$.getJSON('http://localhost/vojto/get_json.php?c_prot=<?=$_REQUEST['
c_prot '];?>', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
chart: { //zooming
zoomType: 'x',
height: 400,
},
legend: { //legenda
enabled: true,
align: 'left',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 1,
layout: 'vertical',
verticalAlign: 'top',
y: 100,
shadow: true
},
rangeSelector: { //range selector
buttonTheme: {
width: 40,
},
buttonSpacing: 3, //mezera mezi buttony
enabled: true,
buttons: [{
type: 'minute',
count: 60,
text: 'Hour'
}, {
type: 'day',
count: 1,
text: 'Day'
}, {
type: 'week',
count: 1,
text: 'Week'
}, {
type: 'all',
text: 'Reset'
}]
},
title: { //title grafu
text: 'Chart'
},
series: [{ //serie
name: 'Data',
data: data,
color: '#57c72f',
marker: {
enabled: true,
radius: 3
},
shadow: true,
tooltip: {
valueDecimals: 2
}
}],
xAxis: { // X-osa
type: 'datetime',
title: {
text: 'Date/time axis',
},
minRange: 600000,
},
yAxis: {
min: 0,
},
navigator: {
series: {
color: '#57c72f',
fillOpacity: 0.3,
}
},
credits: {
enabled: false
},
tooltip: { // formátování hodnot po najetí kurzoru... hover
formatter: function () {
var s = '<b>' + Highcharts.dateFormat('DateTime ' + '%d-%m-%y ' + '%H:%M:%S', this.x) + '</b>';
$.each(this.points, function (i, point) {
s += '<br/>Data value : ' + point.y;
});
/* formát 23-04-13 09:34:27 */
return s;
}
},
});
});
});
</script>
In you script:
$array = [];
while($row = mysql_fetch_array($result)){
$date= strtotime($row['cas'])*1000; // timestamp
$values=hexdec($row['data']); // series1
$val=hexdec($row['src']); // series2
$array[0][]=array($date, $values); //output array
$array[1][]=array($date ,$val);
}
You need paste values to appropriate series index. In other words you can prepare your $array() and add point to one of series. To be honest I have no data so It is only concept.

Unable to SAVE data using proxy in ExtJS

Proxy update on ExtJS is not loading my update API instead it loads URL which I use to display data on GRID.
<script type="text/javascript">
Ext.onReady(function () {
var CoventryItemListStore = new Ext.data.Store({
storeId: CoventryItemListStore,
autoSave: true,
writer: new Ext.data.JsonWriter(),
reader: new Ext.data.JsonReader({
idProperty: 'id',
root: 'variables'
}, [{
name: 'id'
}, {
name: 'itemid'
}, {
name: 'triggerQuantity'
}, {
name: 'lastUpdatedBy'
}, {
name: 'lastUpdatedOn'
}]),
proxy: new Ext.data.HttpProxy({
method: 'POST',
prettyUrls: false,
url: '/admin/loadCoventryItemApprovalList.epm',
api: {
update: '/admin/updateCoventryItemApprovalList.epm'
}
}),
listners: {
'write': function (store, action, result, res, rs) {
if (action == 'update') {
var newId = res.raw.newId;
var oldId = res.raw.oldId;
if (newId != oldId) {
CoventryItemListStore.reload();
}
}
}
}
});
CoventryItemListStore.load();
var fm = Ext.form;
var CoventryItemListGridUi = Ext.extend(Ext.grid.EditorGridPanel, {
title: 'Coventry Item List',
store: CoventryItemListStore,
width: 980,
height: 650,
renderTo: 'coventryDiv',
defaults: {
width: 280
},
defaultType: 'textfield',
stripeRows: true,
// reader: CoventryItemListReader,
autoExpandColumn: 'coventryListCol',
align: 'center',
clicksToEdit: 1,
initComponent: function () {
this.columns = [{
xtype: 'gridcolumn',
header: 'ID',
sortable: true,
dataIndex: 'id'
}, {
xtype: 'gridcolumn',
header: 'ITEM ID',
sortable: true,
width: 250,
align: 'center',
dataIndex: 'itemid'
}, {
xtype: 'gridcolumn',
header: 'TRIGGER QUANTITY',
sortable: true,
// id: 'ftpCol',
width: 200,
align: 'center',
dataIndex: 'triggerQuantity',
editor: {
xtype: 'numberfield'
}
}, {
xtype: 'gridcolumn',
header: 'LAST UPDATED BY',
sortable: true,
width: 80,
align: 'center',
dataIndex: 'lastUpdatedBy',
id: 'coventryListCol'
}, {
xtype: 'gridcolumn',
header: 'LAST UPDATED ON',
sortable: false,
width: 100,
align: 'center',
dataIndex: 'lastUpdatedOn',
}];
this.listeners = {
'afteredit': function (e) {
params: {
var oldVal = e.originalValue;
var newVal = e.value;
var fieldName = e.field;
var itemID = e.record.get("itemid");
}
alert('Field \'' + fieldName + '\' changed from \'' + oldVal + '\' to \'' + newVal + '\'.(itemID: ' + itemID + ')');
}
}
var itemsPerPage = 100;
this.bbar = new Ext.PagingToolbar({
pageSize: itemsPerPage,
autoLoad: true,
store: CoventryItemListStore,
displayInfo: true,
displayMsg: 'Displaying categories {0} - {1} of {2}',
emptyMsg: "No categories to display"
});
this.tbar = new Ext.Toolbar({
xtype: 'toolbar',
items: [{
xtype: 'textfield',
id: 'searchValue'
}, {
xtype: 'button',
text: 'Search',
style: 'marginLeft: 5px',
enableToggle: true,
handler: function () {
vms.reload({
params: {
searchValue: Ext.getCmp('searchValue').getValue()
}
});
}
}]
});
CoventryItemListGridUi.superclass.initComponent.call(this);
}
});
new CoventryItemListGridUi();
});
</script>
well re posting the answer for better visibility
proxy: new Ext.data.HttpProxy({ method: 'POST', prettyUrls: false, url: '/admin/updateCoventryItemApprovalList.epm', api: { read: '/admin/loadCoventryItemApprovalList.epm' } })