My Candlestick chart imports data from a json file. Everything is great when I don't mess with the file
But when I use php to exclude some json rows to filter the data, I will end up with this even when every value on chart is correct.
How can I fix it?
My settings
(function () {
// $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?a=e&filename=aapl-ohlc.json&callback=?', function (data) {
$.getJSON(<?php echo "'getJSON.php?symbol=" . $_GET["symbol"] . "&timeframe=" . $_GET["timeframe"] . "'"; ?>, function (data) {
// create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1,
buttons: [{
type: 'minute',
count: 1,
text: '1m'
}, {
type: 'minute',
count: 5,
text: '5m'
}, {
type: 'minute',
count: 30,
text: '30m'
}, {
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'hour',
count: 5,
text: '5h'
}, {
type: 'all',
text: 'All'
}]
},
title : {
text : <?php echo "'" . $_GET["symbol"] . " Price | " . $_GET["timeframe"] . "M'" ?>
},
series : [{
type : 'candlestick',
name : <?php echo "'" . $_GET["symbol"] . " Price'"; ?>,
data : data,
dataGrouping : {
enable: false
}
}]
});
});
});
Related
I push array outside loop with (cpu_usage, timestamp and clientID).Now i want to read on console log values of clientID console.log(result[0][2]); .But it shows me a error "Cannot read property '2' of undefined". Is someone knows where is a problem ? Also if i call this array inside loop it works
content of array:
error after i used console.log(result[0][2]);
<div id="cont"></div>
<script type="text/javascript">
$.getJSON( "http://localhost:8000/api/devices", function( res) {
var result= [];
var devNames = new Array();
console.log(result[0][2]);
$.each( res, function(i) {
var deviceNames=data[i].clientAllias;
var clientId=data[i].clientId;
devNames .push(deviceNames);
$.each( res[i].clientData, function(a) {
$.each( res[i].clientData[a], function(key, val) {
clientId2=res[i].clientData[a].clientId
var cpu=res[i].clientData[a].cpuUsage;
var time_usages=res[i].clientData[a].timestamp;
final=[];
final.push(time_usages, cpu, clientId2);
result.push(final);
});
});
});
result.sort();
$(document).ready(function(){
var Object = {
marker: {
states: {
enabled: true,
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: 'Sec'
}, {
count: 1,
type: 'hour',
text: 'Min'
},
{
count: 1,
type: 'day',
text: 'Hours'
},
{
type: 'all',
text: 'All'
}],
title:'hours',
inputEnabled: true,
_selected: 1
},
title: {
text: clientNames,
},
xAxis: {
title: {
enabled: true,
text: 'CPU USAGE'
},
type: 'datetime',
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
},
},
plotOptions: {
series: {
marker: {
enabled: false,
}
}
},
series: [{
name:"CPU USAGE",
data: result,
}],
chart: {
renderTo: 'cont'
}
};
var chart = new Highcharts.StockChart(dataObject);
//var chart = $('#container').highcharts('StockChart', dataObject);
});
});
</script>
You’re console logging at the wrong spot. There’s nothing in result when you’re logging so it errors out when you try to access a nested element.
Put the console log at the end (after result.sort()) and you should get what you need
I can't use foreach php code in javascript code of registerJS in yii2. Browser shows "PHP Parse Error – yii\base\ErrorException syntax error, unexpected 'foreach' (T_FOREACH)" error. Here is my code:
<canvas id="bar-chart" width="500" height="150"></canvas>
<?php
$lang = Yii::$app->language;
$title = 'title_'.$lang;
$this->registerJs("
new Chart(document.getElementById('bar-chart'), {
type: 'bar',
data: {
labels: [
" . foreach ($models as $model) { . "
' " . $model->$title . " ',
" . } . "
],
datasets: [
{
label:'Label',
backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'],
data: [479,1654,499, 2632]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Title'
}
}
});
", yii\web\View::POS_READY);
I'll pull out foreach code from javascript output.
<?php
$titles = [];
foreach($models as $model)
{
$titles[] = sprintf("'%s'", $model->title);
}
$titlesText = implode(',', $titles);
$this->registerJs("
new Chart(document.getElementById('bar-chart'), {
type: 'bar',
data: {
labels: [
".$titlesText."
],
datasets: [
{
label:'Label',
backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'],
data: [479,1654,499, 2632]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Title'
}
}
});
", yii\web\View::POS_READY);
You cannot use the foreach statement there, in the middle of a string. You should generate the string coming from the foreach beforehand and then join it with the js string:
$mystring = "";
foreach ($models as $model) {
$mystring .= "' " . $model->$title . " ',";
}
$this->registerJs("
new Chart(document.getElementById('bar-chart'), {
type: 'bar',
data: {
labels: [ $mystring ],
datasets: [
{
label:'Label',
backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'],
data: [479,1654,499, 2632]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Title'
}
}
});
", yii\web\View::POS_READY);
I am using this code to render a HighChart:
<script>
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container1',
title: '',
type: 'column'
},
xAxis: {
categories: ["<?php echo join($data0, '","') ?>"],
title: {
text: 'Month'
}
},
yAxis: {
title: {
text: 'Orders'
}
},
series: [{
name: '<?php echo date("Y",strtotime("-1 year")); ?>',
color: '#666666',
data: [<?php echo join($data1, ',') ?>]
}, {
name: '<?php echo date("Y"); ?>',
color: '#2196F3',
data: [<?php echo join($data2, ',') ?>]
}],
credits: {
enabled: false
},
title: {
text: ''
}
});
</script>
How can get this to update every 5 seconds and show some indication on the chart if something changes?
Try
setInterval(function(){
chart.series[0].update({
data: [<?php echo join($data1, ',') ?>]
}, true);
chart.series[1].update({
data: [<?php echo join($data2, ',') ?>]
}, true);
}, 5000);
i get my JSON object from my php code in this format (JSONlint ok) :
[
[1375653600000,3.20104,175.00,116.00,11.00,31.00],[...],[1376776800000,2.85625,10.00,1.00,0.00,8.00]
]
i Have to split in 5 different series:
[1375653600000, 3.201014]
[1375653600000, 175.00]
[1375653600000, 116.00]
[1375653600000, 11.00]
[1375653600000, 31.00]
...
and (obviously) each array is for a different highcharts series.
i follow this post to get an idea about split the JSON:
Retrieving JSON data for Highcharts with multiple series?
This is my code:
$(function() {
// See source code from the JSONP handler at https://github.com/highslide-software/highcharts.com/blob/master/samples/data/from-sql.php
$.getJSON('grafico_nuovo.php?callback=?', function(data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2012, 9, 14, 19, 59), null, null, null, null]]);
// create the chart
$('#container').highcharts('StockChart', {
chart : {
type: 'spline',
zoomType: 'xy'
},
navigator : {
adaptToUpdatedData: false,
series : {
data : data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'analisi consumi e temperature'
},
subtitle: {
text: 'Analisi test solo temperatura media'
},
rangeSelector : {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 2,
text: '2d'
}, {
type: 'week',
count: 1,
text: '1w'
},{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true, // it supports only days
selected : 2 // day
},
/*xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},*/
xAxis: {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000, // one hour
type: 'datetime',
dateTimeLabelFormats: { minute: '%H:%M', day: '%A. %e/%m' },
// minRange: 15*60*1000,
//maxZoom: 48 * 3600 * 1000,
labels: {
rotation: 330,
y:20,
staggerLines: 1 }
},
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
},
{
name: 'val3',
data: []
},
{
name: 'val4',
data: []
},
{
name: 'val5',
data: []
}]
});
});
});
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var currentExtremes = this.getExtremes(),
range = e.max - e.min,
chart = $('#container').highcharts();
chart.showLoading('Loading data from server...');
$.getJSON('grafico_nuovo.php?start='+ Math.round(e.min) +
'&end='+ Math.round(e.max) +'&callback=?', function(data) {
val1 = [];
val2 = [];
val3 = [];
val4 = [];
val5 = [];
$.each(data, function(key,value) {
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
val3.push([value[0], value[3]]);
val4.push([value[0], value[4]]);
val5.push([value[0], value[5]]);
});
console.log('val1');
chart.series[0].setData(val1);
chart.series[1].setData(val2);
chart.series[2].setData(val3);
chart.series[3].setData(val4);
chart.series[4].setData(val5);
chart.hideLoading();
});
}
The navigator works fine (with little trouble after 3-4 clicks) but the other series doesn't show.
Everything should be ok, but i've probably missed something
How to pass an jquery ajax response after success into a php variable. this is my code :
process.php
$start = "";
$end = "";
if(isset($_POST['tampStart']))
{
$start = $_POST['tampStart'];
}
if(isset($_POST['tampEnd']))
{
$end = $_POST['tampEnd'];
}
$SQL = "SELECT * FROM `values` WHERE date BETWEEN '".$start."' and '".$end."'";
$result = mysql_query($SQL);
$prefix = '';
while ( $row = mysql_fetch_assoc( $result ) ) {
$prefix .= "[\n"."'".$row['month']."'".', '.$row['days']."]".",";
}
echo rtrim($prefix, ",");
index.php
var dStart = $('#textInput1').val();
var dEnd = $('#textInput2').val();
var form_data = {
tampStart: dStart,
tampEnd: dEnd
};
$.ajax({
url: 'process.php',
type: 'POST',
async : true,
data: form_data,
dataType: 'text',
success: function(resp){
$('#content').html(resp);
//pass to php variable ?
}
});
there is no problem when I put the response into a div ($('#content').append(resp);), but how to put the response into an php variable. Thanks for advance..
update my Highcharts code :
function createChart(datan) {
//alert(datan);
Highcharts.setOptions({
lang: {
drillUpText: 'Back to {series.name}'
}
});
var options = {
chart: {
height: 300
},
title: {
text: 'Highcharts Drilldown Plugin'
},
xAxis: {
categories: true
},
drilldown: {
series: [{
id: 'fruits',
name: 'Fruits',
data: [datan] //here #*
}, {
id: 'cars',
name: 'Cars',
data: [{
name: 'Toyota',
y: 4,
drilldown: 'toyota'
},
['Volkswagen', 3],
['Opel', 5]
]
}, {
id: 'toyota',
name: 'Toyota',
data: [
['RAV4', 3],
['Corolla', 1],
['Carina', 4],
['Land Cruiser', 5]
]
}]
},
legend: {
enabled: false
},
plotOptions: {
series: {
dataLabels: {
enabled: true
},
shadow: false
},
pie: {
size: '80%'
}
},
series: [{
name: 'Overview',
colorByPoint: true,
data: [{
name: 'Fruits',
y: 10,
drilldown: 'fruits'
}, {
name: 'Cars',
y: 12,
drilldown: 'cars'
}, {
name: 'Countries',
y: 8
}]
}]
};
// Column chart
options.chart.renderTo = 'container1';
options.chart.type = 'column';
var chart1 = new Highcharts.Chart(options);
}
I make the highcharts config to a function. when I alert(datan), its shown the data from ajax response, but when I put on Drilldown option data (see sign #* above), the highchart config cant read it..
PHP runs on server not on client so the thing you asking is possible only on server. You have to customize this code for your need it gives framework.
$.ajax({
url: 'process.php',
type: 'POST',
async : true,
data: form_data,
dataType: 'text',
success: function(resp){
// $('#content').html(resp);
createChart(resp);
}
});
var chart;
function createChart(data) {
var options = {
chart: {
height: 300
},
title: {
text: 'Highcharts Drilldown Plugin'
},
xAxis: {
categories: true
},
drilldown: {
series: data}
};
options.chart.renderTo = 'content';
options.chart.type = 'column';
var chart1 = new Highcharts.Chart(options);
}
Javascript is a client side scripting. You can't assign the javascript value directly to the php variable.
One way is to set a SESSION variable in PHP. In your case in process.php file.
Another way is to use Database/files.
Well, if you really want to do it this way, you can set a cookie with the desired variable in Javascript and afterwards access it with PHP.
But, there is another way. You can do whatever you want on the client side and when you want to transmit the variable to server-side, just open an ajax connection on the php page which will handle the variable and hand it the actual variable through POST data.