Dynamically create chart with Chart.js and PHP - javascript

We're currently using customerthermometers to survey our customers after completed support-tickets. Unfortunately customerthermometers widget's look disgusting. So I'm currently trying to create a chart with Chart.js and dynamically getting data from customerthermometers' API with PHP.
All parts in the PHP-array ($dataPoints) is taken into account in the chart, except the "data", and I really don't know how to proceed further.
<?php
$gold = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=1' );
$green = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=2' );
$yellow = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=3' );
$red = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=4' );
$dataPoints = array(
array( "label" => "Gold Star" , "data" => $gold , "backgroundColor" => "rgba(255,215,0,1)"),
array( "label" => "Green Light" , "data" => $green , "backgroundColor" => "rgba(0,128,0,1)"),
array( "label" => "Yellow Light" , "data" => $yellow , "backgroundColor" => "rgba(255,255,0,1)"),
array( "label" => "Red Light" , "data" => $red , "backgroundColor" => "rgba(255,0,0,1)" )
);
?>
<html>
<head>
<meta charset="utf-8">
<title>Chart Test</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../assets/chart28/dist/Chart.js"></script>
<canvas id="myChart" width="100" height="20"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Gold Star', 'Green Light', 'Yellow Light', 'Red Light'],
datasets: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
</body>
</html>
Edit:
$dataPoints
[{"label":"Gold Star","data":4,"backgroundColor":"rgba(255,215,0,1)"},{"label":"Green Light","data":2,"backgroundColor":"rgba(0,128,0,1)"},{"label":"Yellow Light","data":0,"backgroundColor":"rgba(255,255,0,1)"},{"label":"Red Light","data":0,"backgroundColor":"rgba(255,0,0,1)"}]
I've also tried to statically set the following values within datasets, and this works and gives me the desired result:
datasets: [{
data: [ 4 , 2 , 0 , 0 ],
backgroundColor: [
"rgba(255,215,0,1)",
"rgba(0,128,0,1)",
"rgba(255,255,0,1)",
"rgba(255,0,0,1)"
]
}]
Working code (Thanks to #Camille):
<?php
$gold = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=1' );
$green = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=2' );
$yellow = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=3' );
$red = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=4' );
$dataPoints = array(
array( "data" => array($gold) , "label" => "Gold Star" , "backgroundColor" => "rgba(255,215,0,1)"),
array( "data" => array($green) , "label" => "Green Light" , "backgroundColor" => "rgba(0,128,0,1)"),
array( "data" => array($yellow) , "label" => "Yellow Light" , "backgroundColor" => "rgba(255,255,0,1)"),
array( "data" => array($red) , "label" => "Red Light" , "backgroundColor" => "rgba(255,0,0,1)" )
);
?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../assets/chart28/dist/Chart.js"></script>
<canvas id="myChart" width="100" height="20"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Customer Thermometer'],
datasets: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
</script>
</body>
</html>

Data attribute of $dataPoints should be an array. You have to convert it if you get a single value
...
$dataPoints = array(
array( "label" => "Gold Star" , "data" => array($gold) , "backgroundColor" => "rgba(255,215,0,1)"),
array( "label" => "Green Light" , "data" => array($green) , "backgroundColor" => "rgba(0,128,0,1)"),
array( "label" => "Yellow Light" , "data" => array($yellow) , "backgroundColor" => "rgba(255,255,0,1)"),
array( "label" => "Red Light" , "data" => array($red) , "backgroundColor" => "rgba(255,0,0,1)" )
);
...

Related

How to make a correct json to provide data to Apexcharts pie?

I'm new in Apexcharts, and I try to make a pie chart with data, getting from mysql database. This is the php-file named "get_types_chart.php"
$year = date('Y');
$month = date('m');
$graf = PDO()->prepare("SELECT COUNT(tickets.id) AS cid, types.ticket_type AS type_name FROM tickets LEFT JOIN types ON tickets.type=types.id WHERE tickets.arch=0 AND tickets.status NOT IN (2, 4) AND MONTH(tickets.date_create)=:month AND YEAR(tickets.date_create)=:year GROUP BY types.ticket_type");
$graf->execute([':year' => $year,
':month' => $month]);
$arrData = array();
while($row = $graf->fetch(PDO::FETCH_LAZY)) {
array_push($arrData, array(
"labels" => $row->type_name,
"series" => $row->cid
)
);
}
$jsonEncodedData = json_encode($arrData);
header('Content-Type: application/json');
echo $jsonEncodedData;
And this is the js-code:
var url3 = 'charts/get_types_chart.php';
var options3 = {
series: [],
chart: {
width: 380,
type: 'pie',
},
title: {
text: '<?php echo lang('MON_STAT_year'); ?>',
floating: true,
align: 'center'
},
labels: [],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart3 = new ApexCharts(document.querySelector("#chart3"), options3);
chart3.render();
$.getJSON(url3, function(response) {
chart3.updateSeries([{
name: '<?php echo lang('DASH_STAT_month_all'); ?>',
data: response
}])
});
Finally I get empty pie. Please hel me to make a correct json.

Php Array to line chart in ChartJs

$days = ["Monday","Tuesday","Wednesday"];
$rates = [40,60,80];
$profit = [];
foreach($days as $day => $value){
foreach($rates as $rate){
$netprofit = $rate* 20;
$profit[$value] = [$rate=> $netprofit];
}
}
$usersChart = new UserChart;
$usersChart->labels($days);
foreach($profit as $key => $value){
$data = array();
foreach ($value as $values){
$data[] = $values;
}
$usersChart->dataset($key, 'line', collect($data));
}
I want to show this array into Chartjs Line Graph. I want the x axis to be the 40,60,80. Y axis to be 800, 1200, 1600. The Dataset or Lines should be Monday, Tuesday and Wednesday.
Right now i get Monday, Tuesday and Wednesday as x axis and Line. 600,800 etc are on y axis.
Array
(
[Monday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Tuesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Wednesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
)
keep your array as it is and convert it to JSON object and then echo it inside Javascript, javascript have to be inside php file to run, not in external javascript file.
notice that there is PHP code in this example and i have put <?php echo $json; ?> inside the javascript code.
<html>
<head>
<style>body{width: 800px;}</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div>
<canvas id="myChart" width="700px" height="300px"></canvas>
</div>
<?php
$array = array(600, 800, 1200, 1800);
$json = json_encode($array);
?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["20", "40", "60", "80"],
datasets: [
{
label: 'Monday',
borderColor: "#FF9F40",
data: <?php echo $json; ?>,
},
{
label: 'Tuesday',
borderColor: "#FF6384",
data: [600, 800, 1200, 1800]
},
{
label: 'Wednesday',
borderColor: "#219151",
data: [600, 800, 1200, 1800]
}
]
},
// Configuration options go here
options: {}
});
</script>
</body>
</html>

Change location of a graph

I have 3 graphs and I want to put one of them to another place on the local host screen. But I'm a beginner on php and I have no idea is it possible or how can I do that. Can you give me any advice for it ? How can I do that ? Thanks.
My HTML codes:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "RR Interval Time Series"
},
data: [
{
type: "line",
dataPoints: [
<?PHP
foreach($arr as $key => $v){
$output[] = "{ x: " . $x[$key] . ", y: " . $v . " }";
}
echo implode(",\n", $output);
?>
]
}
]
});
var data = <?php echo json_encode($wshort, JSON_NUMERIC_CHECK); ?>;
data = data.map(function (row, index) {
return {
x: index,
y: row
};
});
var chart2 = new CanvasJS.Chart("chartContainer2", {
title: {
text: "FFT Results"
},
data: [{
type: "line",
dataPoints: data
}]
});
var chart3 = new CanvasJS.Chart("chartContainer3",
{
title:{
text: "Poincare Plot"
},
data: [
{
type: "scatter",
dataPoints: [
<?PHP
foreach($pointy as $key1 => $v1){
$output1[] = "{ x: " . $pointx[$key1] . ", y: " . $v1 . " }";
}
echo implode(",\n", $output1);
?>
]
}
]
});
chart.render();
chart2.render();
chart3.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 200px; width: 70%;">
</div>
<div id="chartContainer2" style="height: 200px; width: 70%;">
</div>
<div id="chartContainer3" style="height: 300px; width: 30%;">
</div>
</body>
</html>
I need to change position of "chartContainer3". Should I do something with div style ?

Wrong date in highstock Chart

How can I incorporate the correct date into my high stock chart? I keep getting the months January to February (correct range should be from July to August) in my slider, which is incorrect. In my PHP I convert the date/time from my database into a JavaScript timestamp, but still doesn't work. Any help would be great, thanks!
Output Array: data.txt
Current high stocks Chart:
PHP & JS and HTML:
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = $date;
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>
<!DOCTYPE html>
<html >
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script>
$(function(data) {
$('#chart2').highcharts('StockChart', { //Stock chart - might need zones to match gauges
rangeSelector : {
buttons : [{
type : 'hour',
count : 3,
text : '3h'
}, {
type : 'day',
count : 2,
text : '2D'
}, {
type : 'week',
count : 1,
text : '1W'
}, {
type : 'month',
count : 1,
text : '1M'
}, {
type : 'all',
count : 1,
text : 'All'
}],
selected : 2,
},
title: {
text: 'Power'
},
yAxis: [{
title: {
text: 'Bat V'
},
height: 400,
lineWidth: 2,
oposite: true
}, {
title: { // yAxis 1 ie secondary y-axis
text: 'Solar V'
},
//top: 200,
height: 400,
offset: 25,
lineWidth: 2,
oposite: false
}],
xAxis:{
type: <?php echo json_encode($time) ?>,
},
series: [{
pointInterval: 24 * 3600 * 1000,
type: 'line',
data: <?php echo json_encode($result['AT']) ?>
},],
}); //end of stockchart graphic
// end of get function
}); // end of graphing function
</script>
</head>
<body>
<?php echo $time; ?>
<br><br /><br /><br />
<div id="chart2" style="width:100%; height:600px;"></div>
</body>
</html>
Based on your Output Array: data.txt which is [["2017-07-25 16:44",12],["2017-07-25 17:00",12],...] it should be [[1500981240000,12],[1500982200000,12],...] so fix is $result['date'][] = strtotime($date)*1000 get unix timestamp in milliseconds
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = strtotime($date)*1000; // get unix timestamp in milliseconds
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>

Highstock don't draw

http://www.highcharts.com/stock/demo/basic-line
It's my code for json.php
<?php
header("content-type: application/json");
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', 'password');
define('NAME_BD', 'bd');
$connect = mysql_connect(HOST, USER, PASSWORD)
or die("die"
.mysql_error( ));
mysql_select_db(NAME_BD, $connect)
or die ("wtf"
.mysql_error( ));
$result = mysql_query("SELECT UNIX_TIMESTAMP(`Time`) * 1000 as datetime, `Current A` as A FROM `Table`")
or die ("die".mysql_error( ));
while ($row = mysql_fetch_array($result)) {
$data[] = $row['datetime'];
$datab[] = $row['A'];
}
echo '?(' . "\n" . '['. "\n";
$count = count($data);
for ($i=0; $i<$count; $i++)
{
echo '['. str_replace('"', "", json_encode($data[$i], JSON_HEX_APOS)) . ',' . str_replace('"', "", json_encode($datab[$i], JSON_HEX_APOS)) .']' . ',' . "\n";
}
echo ']);';
?>
I refresh my page and highstock don't draw. Please help me.
It's my stock.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$.getJSON('http://192.168.1.175/json.php', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data
}]
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
Stock.html call json.php but when a refresh stock.html i don't see draw.
Please help me
Please try below code
in Ajax code
function drawGrap()
{
$.ajax({
type: "POST",
url: 'graph.php',
data: '',
success: function(json) {
drawSalesChart(json);
}
});
}
in graph.php
<?php
if(!empty($data))
{
foreach ($data as $d)
{
$time = strtotime($d['date']);
$date = date("Y-m-d",$time);
$graphData[$date][0] = 'Date.UTC('. date("Y",$time) .','. (date("m",$time)-1) .','. date("d",$time) .')';
$graphData[$date][1] = $d['count'];
}
}
sort($graphData);
//Convert result array to json format
$jsonGraphData = json_encode($graphData);
$jsonGraphData = str_replace('"', '', $jsonGraphData);
echo $jsonGraphData;
?>
After response
function drawSalesChart( data)
{
$('#GraphID').css("height", "400px");
$('#GraphID').highcharts('StockChart', {
title: {
text: 'Daily Sales'
},
colors: ['#920000'],
navigator: {
enabled: false
},
rangeSelector: {
selected: 5,
buttons: [
{
type: 'week',
count: 1,
text: '1 Week'
},
{
type: 'month',
count: 1,
text: '1 Month'
},
{
type: 'month',
count: 3,
text: '3 Months'
},
{
type: 'month',
count: 6,
text: '6 Months'
},
{
type: 'year',
count: 1,
text: '1 Year'
},
{
type: 'all',
text: 'All'
}
],
buttonTheme: {
width: 100,
padding: 5,
style: {
color: '#000000'
}
}
},
series: [{
name: 'Kr',
type: 'area',
data: eval(data),
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#FF4848'],
[1, '#ffe1e1'],
]
}
}]
});
}

Categories

Resources