javascript chart data from different php file? - javascript

I have a chart.html that will show some chart and I try to use echo json_encode to get data from PHP, but the PHP is in different file , How can I define the process.php in order to let chart.html get the data ?
chart.html :
<div id="chart_donut" style="height:350px;"></div>
<script>
var chart = echarts.init(document.getElementById('chart_donut'), theme);
trapchart.setOption({
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
calculable: true,
legend: {
x: 'center',
y: 'bottom',
data: <?php echo json_encode($ary, JSON_PRETTY_PRINT);?>
}, ///??????get data from process.php
toolbox: {
show: true,
feature: {
magicType: {
show: true,
type: ['pie', 'funnel'],
option: {
funnel: {
x: '25%',
width: '50%',
funnelAlign: 'center',
max: 1548
}
}
},
restore: {
show: true,
title: "Restore"
},
saveAsImage: {
show: true,
title: "Save Image"
}
}
},
series: [{
name: 'Access to the resource',
type: 'pie',
radius: ['35%', '55%'],
itemStyle: {
normal: {
label: {
show: true
},
labelLine: {
show: true
}
},
emphasis: {
label: {
show: true,
position: 'center',
textStyle: {
fontSize: '14',
fontWeight: 'normal'
}
}
}
},
data: <?php echo json_encode($results, JSON_PRETTY_PRINT);?>
//?????get from process.php
}]
});
</script>

First you need chart.html to be a php file otherwise will not execute php scripts.
Your process.php should be included at the top of this chart.php
;
process.php should have someting like this
//get the data for both arrays
$ary = ..
$results = ...

Related

Real time data display in highcharts

I want to display real time data in highcharts from my MYSQL database, I have tried methods like setInterval and setTimeout and chart.redraw() but cant seem to make it work.
I have also tried the dynamic update chart in highcharts link is here : enter code herehttps://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/demo/dynamic-update but cant seem to convert random data syntax to my database data. my code is :
<html>
<head>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js">
</script>
<script src="https://code.highcharts.com/stock/modules/drag-panes.js">
</script>
<link rel="stylesheet" type="text/css" href="/public/oi chart.css">
</head>
<figure class="highcharts-figure">
<div id="container"></div>
</figure>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.stockChart('container', {
options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
Highcharts.stockChart('container', {
rangeSelector: {
enabled: true,
selected: customRange,
buttons: [{
type: 'day',
count: 1,
text: '1D'
}, {
type: 'week',
count: 1,
text: '1W'
}, {
type: 'week',
count: 2,
text: '2W'
}, {
type: 'month',
count: 1,
text: '1M'
}, {
type: 'all',
text: 'All'
}]
},
time: {
timezoneOffset: timezone
},
events: {
load: function requestData() {
$.ajax({
url: 'temp_chart.js',
success: function(points) {
var series = chart.series,
shift;
$.each(series, function(i, s) {
shift = s.data.length > 1;
s.addPoint(points[i], true, true);
});
setTimeout(requestData, 1000);
chart.redraw();
},
cache: false
});
}
},
title: {
text: 'Temperature',
},
subtitle: {
text: 'temperature in maharashtra',
},
yAxis: {
title: {
text: 'temperature'
},
resize: {
enabled: true
}
},
xAxis: {
type: 'datetime'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
marker: {
enabled: false
},
label: {
connectorAllowed: false
},
}
},
series: [{
name: 'Mumbai',
data: []
}, {
name: 'Pune',
data: []
}],
};
$.getJSON('temp_chart.js', function(json) {
data1 = [<% data array %>];
data2 = [<% data array %>];
$.each(json, function(key, value) {
data1.push([value[0], value[1]]);
data2.push([value[0], value[2]]);
});
options.series[0].data = data1;
options.series[1].data = data2;
chart = new Highcharts.stockChart(options);
});
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</html>~
Notice that the load callback should be nested in the chart.events object config. API: https://api.highcharts.com/highcharts/chart.events.load

Highcharts Column with php

well im with a problem with a Highchart Graphic. This one -> http://www.highcharts.com/demo/column-basic
I have a database with a table call "Days" and "Works" and i want to put the days that i have in the "categories []" and the work in series[];
BUT
i dont know how my JSON need to be, or the best way to do it is with a JS array
I tried this way:
js_array = new Array(<?php echo implode(',', $array1); ?>);
xAxis: {
categories: js_array,
crosshair: true
},
or just categories:<?php echo json_encode($array1);?>
but dont succeed.
can you help me?
I do this using asp.net (MVC5), but I think is the same idea for php, hope it helps.
<script>
$(function () {
var chart = new Highcharts.Chart({
chart: {
type: 'column',
renderTo: 'container'
},
title: {
text: "Client's downloads"
},
subtitle: {
text: 'Click the columns to view products.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total downloads'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b><br/>'
},
series: [{
name: "Downloads",
colorByPoint: true,
data: [
#foreach (var item in Model)
{
<text>{</text>
<text>name: "</text> #item.Name <text>",</text>
<text>y: </text> #item.Downloads <text>,</text>
<text>drilldown: "</text>#item.Name<text>"},</text>
}
]
}],
drilldown: {
series: [
#foreach (var item in Model)
{
<text>{</text>
<text>name: "</text>#item.Name<text>",</text>
<text>id: "</text>#item.Name<text>",</text>
<text>data: [</text>
foreach (var download in item.ProductDownloads)
{
<text>["</text> #download.Product <text>", </text> #download.Downloads <text>],</text>
}
<text>]</text>
<text>},</text>
}
]
}
});
});
</script>

Pass data as a js variable to highchart

I have a associate php array (field_data) and i wanna pass it to JS using json_encode function: $jArray = json_encode($field_data);
I'm recieving the array in JS: var irbrowser = <?php echo $jArray; ?>; But in js when i wanna set the value in jArray to pie chart data, It does not render anything.
<?php
$jArray = json_encode($field_data);
?>
<div dir="ltr" id="container"> </div>
<script>
var irbrowser = <?php echo $jArray; ?>;
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: [{
name: "IE",
y: irbrowser.IE
}, {
name: "Chrome",
y: irbrowser.Chrome,
sliced: true,
selected: true
}, {
name: "Proprietary or Undetectable",
y: irbrowser.Other
}]
}]
});
});
</script>
I found the problem.
It should be converted to Float. so i use parseFloate(irbrowser) function. And set the variables to y. That code
series: [{
name: "Brands",
colorByPoint: true,
data: [{
name: "IE",
y: parseFloat(irbrowser.IE)
}, {
name: "Chrome",
y: parseFloat(irbrowser.Chrome),
sliced: true,
selected: true
}, {
name: "Proprietary or Undetectable",
y: 0.5
}]
}]
Look at the first few lines of your script
Line 1 you stop the PHP interpreter
Line 2 you attempt a line of PHP ??
Line 3 you start the PHP interpreter
Line 4+ you try to output raw HTML while inside a PHP section
?>
$jArray = json_encode($field_data);
<?php
<div dir="ltr" id="container"> </div>
<script>
var irbrowser = <?php echo $jArray; ?>;
Try
$jArray = json_encode($field_data);
?>
<div dir="ltr" id="container"> </div>
<script>
var irbrowser = <?php echo $jArray; ?>;

Syncfusion JS Chart Custom Tooltip

I'm using Syncfusion JS 12.1.0.43, trying to implement line chart with custom tooltip;
Here is my HTML;
<div id="div-overview-transaction-tooltip" style="display:none;">
<div id="div-transaction-tooltip-value">
<ul>
<li>#point.totalValue#</li>
<li>#point.dataSource.totalValue#</li>
<li>{{:totalValue}}</li>
<li>#series.dataSource.totalValue#</li>
</ul>
</div>
</div>
Here is my example JSON;
{"TotalValue":0,"Percentage":0,"AverageResponseTime":0,"DateTime":"\/Date(1402056000000)\/"}
And here is my JS;
$("#container").ejChart({
primaryXAxis: { labelFormat: "HH:00" },
primaryYAxis:
{
labelFormat: "{value}",
rangePadding: 'round',
range: { min: 0, max: 25, interval: 5 },
},
commonSeriesOptions: {
type: 'line', animation: true,
tooltip: { visible: true, template: 'div-overview-transaction-tooltip' },
marker: { shape: 'circle', size: { height: 5, width: 5 }, visible: true },
border: { width: 1 }
},
series: [{ name: 'GET', type: 'line', dataSource: { data: getJson, xName: "DateTime", yName: 'TotalValue' } }],
canResize: true,
load: "loadTheme",
size: { height: 300 },
legend: { visible: true }
});
Output:
#point.TotalValue#
#point.dataSource.TotalValue#
{{:TotalValue}}
#series.dataSource.TotalValue#
I want to show all of my property from JSON on custom tooltip. Except tooltip everything works fine.
Any help would be appriciated. Thanks already.
By default the Tool-tip template supports only point.x and point.y so there is no direct way to achieve this using Tool-tip template.
However the value "TotalValue" from JSON can be shown in the Tool-tip with the help of the following event "toolTipInitialize" as like in below code snippet.
$("#container").ejChart({
primaryXAxis: { labelFormat: "HH:00" },
primaryYAxis:
{
labelFormat: "{value}",
rangePadding: 'round',
range: { min: 0, max: 25, interval: 5 },
},
commonSeriesOptions: {
type: 'line', animation: true,
tooltip: { visible: true, template: 'div-overview-transaction-tooltip' },
marker: { shape: 'circle', size: { height: 5, width: 5 }, visible: true },
border: { width: 1 }
},
series: [{ name: 'GET', type: 'line', dataSource: { data: getJson, xName: "DateTime", yName: 'TotalValue' } }],
canResize: true,
load: "loadTheme",
size: { height: 300 },
toolTipInitialize:"rendertool"
legend: { visible: true }
});
And in the method "rendertool"
function rendertool(sender) {
sender.Data.currentText = "Total Value:"+sender.model.series[sender.Data.seriesIndex].dataSource.data[sender.Data.pointIndex].TotalValue.toString();
}
The sender of the event has the "model" properties of the chart where you can get the data source of the series and thus you can access any values in the JSON. Hope this works for you.
here is the sample link which I tried to achieve this.
Sample
Thanks

EXtJS chart bar/column not fitting in window container, expanding beyond/out of it

I am using EXtJS charts to chart data and for some reason it is expanding to the right of window containing it and when using columns, above the window. It seems to be a scaling issue as with just one column/bar it scales and fits everything in perfectly.
{
title: title,
closable:true,
collapsible: true,
//width: 600,
height: 400,
layout: 'fit',
store: Ext.create('Ext.data.Store', {
fields : [ 'metrics', 'dimensions' ],
data : [ {'metrics':metrics, 'dimensions':dimensions}
]
}),
tbar: [{
text: 'Save Chart',
handler: function() {
Ext.MessageBox.confirm('Confirm Download', 'Would you like to download the chart as an image?', function(choice){
if(choice == 'yes'){
var chart = Ext.getCmp('barchart');
chart.save({
type: 'image/png'
});
}
});
}
}, {
text : 'Add a Date Range',
handler : function() {
DateMenu.showBy(this,"bl");
dateMenuContext=this;
}
}],
items: [
{
xtype: 'chart',
animate: true,
shadow: true,
style: 'background:#fff',
store: store,
legend: {
position: 'right'
},
axes: [{
type: 'Numeric',
position: axesposition,
fields: x,
title: title+String(" [Metrics: "+String(metrics)).concat(((dimensions!=null)&&(dimensions!=""))? String(", Dimensions: "+dimensions+"]") : "]"),
grid: true,
minimum: 0,
label: {
renderer: function(v) {
return String(v);
}
},
roundToDecimal: false
}, {
type: 'Category',
position: categoryposition,
fields: y,
title: false
}],
series: [{
type: tp,
label : {
display : "outside",
color : '#333',
'text-anchor' : 'middle',
field : x
},
axis: seriesaxisposition,
gutter: 80,
xField: y,
yField: x,
highlight: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
this.setTitle(String(item['yField'])+": "+String(item.value[1]));
}
}
}]
},
]
};
A Ha! I Had to explicitly define type as int in the field for my store/model. It worked fine before, but for some reason this fixed it.
http://www.sencha.com/forum/showthread.php?199952-4.1.0-Stacked-Column-Chart-with-Missing-Y-Value-has-Incorrect-Maximum&p=844595#post844595

Categories

Resources