I'm using Canvasjs to create a candlestick chart. The values are coming from PHP and I use JSON-encode to convert to the javascript array. I recreate the javascript array in the same format as the example, which is this
dataPoints=[{x: new Date(2012,01,01),y:[5198, 5629, 5159, 5385]}]
But the canvas is blank? Here is my code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array("5198", "5629", "5159", "5385"));
$chart_array[] = array("x"=>"2012-01-02","y"=>array("5366", "5499", "5135", "5295"));
$chart_array = json_encode($chart_array);
?>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
console.log(new_array);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
console.log show the array exists. Why is a blank canvas showing? How do I solve?
Y-value in your code seems to be string, which should be numeric. Even if you are storing it as string, parsing it to number before passing it to chart-options will work fine.
Here is the working code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array(5198, 5629, 5159, 5385));
$chart_array[] = array("x"=>"2012-01-02","y"=>array(5366, 5499, 5135, 5295));
$chart_array = json_encode($chart_array);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
Related
I create a chart using canvasjs. Values display in chart is from mysql database. All working but the problem is, it showing just 1 line on chart (sensors_pres) from table SensorData on chart not all three sensors_pres, sensors_temperature_data and sensors_humidity.
Other problem is on range slider is not showing hour from 0 to 24, test it. Click in left-up on button all and in right-up you will see the number -1 to 96. How can i solve?
I opened data.php file with browser and all values working correct.
Here is my html&javascript code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.stock.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("data.php", function (result) {
var stockChart = new CanvasJS.StockChart("chartContainer",{
title:{
text:"StockChart with Numeric Axis"
},
animationEnabled: true,
exportEnabled: true,
charts: [{
axisX: {
crosshair: {
enabled: true,
snapToDataPoint: true
}
},
axisY: {
crosshair: {
enabled: true,
//snapToDataPoint: true
}
},
data: [{
type: "line",
dataPoints: result
}]
}],
rangeSelector: {
inputFields: {
startValue: 00,
endValue: 24,
valueFormatString: "###0"
},
buttons: [{
label: "00",
range: 00,
rangeType: "number"
},{
label: "12",
range: 12,
rangeType: "number"
},{
label: "24",
range: 24,
rangeType: "number"
},{
label: "All",
rangeType: "all"
}]
}
});
stockChart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 450px; width: 100%;"></div>
</body>
</html>
here is my php code:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("fdb30.awardspace.net","3758712_lnd","bogdanutzu97","3758712_lnd");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM SensorData");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['reading_time'] , "y" => $row['sensors_pres'],$row['sensors_temperature_data'],$row['sensors_humidity']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
data: [
{
type: "line",
dataPoints: result1
},
{
type: "line",
dataPoints: result2
},
{
type: "line",
dataPoints: result3
}
]
In your data section add 2 more data sets
I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
x: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.
You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.
Try running this snippet
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
axisX: {
labelAngle: 180
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
label: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.
First time poster, and still relatively new to javascript... I am trying to figure out how to reflect information from a php file to a canvasjs file.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 60, x: 2 },
]
},
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 0, x: 2 },
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Instead of the labels and datapoints etc, I want information from a php file (or how to do it to any type of file) to be collected then displayed into this canvasjs file.
Is there a way to do this?
Sorry if I'm not clear, I really appreciate any help I can get :)
Thanks!
One way would be to make the file you pasted a PHP file, then use PHP in it:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
?>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
},
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Another way would be to create a PHP file that returns the data, and make an AJAX request:
data.php:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
echo json_encode($dataPoints);
ui.html:
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var request = new XMLHttpRequest();
request.onload = function () {
var dataPoints = JSON.parse(request.responseText);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: dataPoints
},
{
type: 'line',
dataPoints: dataPoints
}
]
});
chart.render();
};
request.open('GET', 'data.php', true);
request.send();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
As said in the title, I'm actually making a small application where you can look for a random name into a database and it shows you the adequate chart (the chart that shows the searched name's data).
It works well when I tried that by puting a static name in my data.php file (from where the chart takes the data). But when I used $_GET[ 'search' ] instead it didn't show anything. (I checked my data.php and it returns the JSON correctly) so I guess it comes from HighCharts.
Do you by chance know what could be the problem please?
Here's some parts of my code so you can understand what I'm saying.
data.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=nsui', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql=<<<SQL
SELECT `Period_start_time`, `Segment_Name`,
`csf_bh`, `drp_sd_bh`, `ec_tch_bh`, `ec_hors_cong_bh`
FROM `call_succes`
WHERE `Segment_Name`='{$search}'
SQL;
$reponse = $bdd->query($sql);
$bln = array();
$bln['name'] = 'Period_start_time';
$rows1['name']='csf_bh';
$rows2['name']='drp_sd_bh';
$rows3['name']='ec_tch_bh';
$rows4['name']='ec_hors_cong_bh';
while($donnee=$reponse->fetch()){
$bln['data'][] = $donnee['Period_start_time'];
$rows1['data'][] = $donnee['csf_bh'];
$rows2['data'][] = $donnee['drp_sd_bh'];
$rows3['data'][] = $donnee['ec_tch_bh'];
$rows4['data'][] = $donnee['ec_hors_cong_bh'];
}
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows1);
array_push($rslt, $rows2);
array_push($rslt, $rows3);
array_push($rslt, $rows4);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$reponse->closeCursor();
?>
chart.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container_call',
type: 'line'
},
title: {
text: 'Call Setup Failure',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [],
title: {
text: 'Date'
}
},
yAxis: {
labels: {
format: '{value} %'
},
min: 0,
title: {
text: 'Percentage (%)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '%',
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: []
};
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
});
});
</script>
In my search page I've put a code like :
<?php
...
...
global $search;
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
...
...
$html.=<<<HTML
<div class="box alt">
<div class="row 50% uniform">
<div id="container_call" class="6u 6u(xsmall)">
HTML;
include ('chart.php');
$html.=<<<HTML
</div>
</div>
</div>
...
?>
And of course with the adequate javascript for highcharts etc. When I click on the button search in my home page it redirects me to my search page.
Thank you in advance.