Getting data from MySQL DB using PHP highstock - php

Of some reason I can't seem to get this to work with highstock range selector. The navigator and range selector is not displaying correct data groups. The default data grouping doesn't work. The data displays correct in highcharts:
As you can see, the data grouping doesn't work when clicking on the navigator zoom panel. Also the columns are not increasing
http://marialaustsen.com/htdocs/index.html
What am I missing?
Many thanks
PHP script PDO call
//Checking if a request has been made
if( isset( $_POST ) ) {
//Establishing connection and retrieving the data
try {
$con = new PDO( 'mysql:dbname=output;host=localhost', 'root', 'root' );
$results = $con->query( 'SELECT sent_ecards, date FROM details ORDER BY details.date' );
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
if( isset( $results ) ) {
$data = [];
$categories = [];
$combined = [];
foreach( $results as $row ) {
array_push( $categories, $row['date'] );
array_push( $data, (int) $row['sent_ecards'] );
}
array_push( $combined, $data );
array_push( $combined, $categories );
header( 'Content-Type: application/json' );
echo json_encode( $combined );
}
}
Index file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Send eCards</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="width: 100%; height: 800px;"></div>
<button data-action="retrieve_data">Retrieve New Data</button>
<script>
$(document).ready(function() {
//Sending request to the server on button click
$( '[data-action="retrieve_data"]' ).on( 'click', function( e ) {
e.preventDefault();
$.ajax({
url: 'retrieve-data.php',
type: 'POST',
//async: true,
//dataType: "json",
success: function( data ) {
console.log( data );
var axis = $( '#container' ).highcharts().get( 'datetime' ),
series = $( '#container' ).highcharts().get( 'rewards' );
axis.setCategories( data[1], false );
series.setData( data[0], false );
$( '#container' ).highcharts().redraw();
},
})
//Initializing basic chart configuration object
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
type: 'column',
alignTicks: false
},
title: {
text: 'Send ecards'
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime',
tickInterval:24 * 3600 * 1000 * 365,
labels: {
formatter: function () {
return Highcharts.dateFormat('%b \'%y', this.value);
}
},
title: {
text: 'Date'
},
id: 'datetime'
},
yAxis: {
title: {
text: 'Amount of ecards'
}
},
tooltip: {
valueSuffix: ' K',
useHTML: true,
crosshairs: true,
shared: true,
pointFormat: '<span style="color:{point.color}">\u25CF </span> <b>{point.series.name}: <b>{point.y}</b> ({point.percentage:.1f}%)<br/>',
formatter: function () {
return Highcharts.dateFormat('%A, %b %e, %Y', this.x);
},
},
series: [{
name: 'ecards',
id: 'rewards',
data: [],
pointInterval: 24*3600*1000,
pointStart: Date.UTC(2010,0,1)
}],
});
//$( '#container' ).(chartConfigOptions);
});
});
</script>
</body>
</html>
The data arrays from consol:
(2) [Array(1999), Array(1999)]
0
:
(1999) [843, 2, 544, 81, 45, 12, 454, 81, 45, 466, 3557, 578, 5, 3434, 65, 843, 3435, 544, 65, 843, 4324, 454, 323, 45, 3435, 544, 323, 45, 2, 546, 323, 45, 739, 3557, 342, 235, 2, 546, 342, 235, 565, 342, 235, 2432, 56, 3456, 2432, 56, 2432, 4543, 5, 3456, 2311, 5, 2839, 565, 5, 2839, 65, 4927, 2, 565, 7, 2, 544, 863, 29, 4324, 454, 5, 346, 466, 565, 5, 346, 2311, 454, 264, 68, 343, 546, 29, 4324, 454, 546, 29, 235, 565, 34, 346, 4324, 454, 34, 346, 739, 3557, 34, 346, 98, 454, …]
1
:
(1999) ["01/01/2010", "01/01/2011", "01/01/2012", "01/01/2013", "01/01/2014", "01/01/2015", "01/02/2010", "01/02/2011", "01/02/2012", "01/02/2013", "01/02/2014", "01/02/2015", "01/03/2010", "01/03/2011", "01/03/2012", "01/03/2013", "01/03/2014", "01/03/2015", "01/04/2010", "01/04/2011", "01/04/2012", "01/04/2013", "01/04/2014", "01/04/2015", "01/05/2010", "01/05/2011", "01/05/2012", "01/05/2013", "01/05/2014", "01/05/2015", "01/06/2010", "01/06/2011", "01/06/2012", "01/06/2013", "01/06/2014", "01/06/2015", "01/07/2010", "01/07/2011", "01/07/2012", "01/07/2013", "01/07/2014", "01/08/2010", "01/08/2011", "01/08/2012", "01/08/2013", "01/08/2014", "01/09/2010", "01/09/2011", "01/09/2012", "01/09/2013", "01/09/2014", "01/10/2010", "01/10/2011", "01/10/2012", "01/10/2013", "01/10/2014", "01/11/2010", "01/11/2011", "01/11/2012", "01/11/2013", "01/11/2014", "01/12/2010", "01/12/2011", "01/12/2012", "01/12/2013", "01/12/2014", "02/01/2010", "02/01/2011", "02/01/2012", "02/01/2013", "02/01/2014", "02/01/2015", "02/02/2010", "02/02/2011", "02/02/2012", "02/02/2013", "02/02/2014", "02/02/2015", "02/03/2010", "02/03/2011", "02/03/2012", "02/03/2013", "02/03/2014", "02/03/2015", "02/04/2010", "02/04/2011", "02/04/2012", "02/04/2013", "02/04/2014", "02/04/2015", "02/05/2010", "02/05/2011", "02/05/2012", "02/05/2013", "02/05/2014", "02/05/2015", "02/06/2010", "02/06/2011", "02/06/2012", "02/06/2013", …]

Related

Chartjs.org Displaying different data on Radar Chart tooltip

For example, on the tooltip, I want to show the data for option1 not 2 but 200. Because we show adapted data in the graph. But it will be better to show the real data on the tooltip.
<script>
new Chart(document.getElementById('exampleChartjsRadar').getContext('2d'), {
type: 'radar',
data: {
labels: ["Option1", "Option2", "Option3"],
pointLabelFontSize: 14,
datasets: [{
label: 'Sporcu',
data: [2, 4, 5],
fill: true,
backgroundColor: 'rgba(4, 197, 249, 0.2)',
borderColor: 'rgb(4, 197, 249)',
pointBackgroundColor: 'rgb(4, 197, 249)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(4, 197, 249)'
}]
},
options: {
plugins: {
},
elements: {
line: {
borderWidth: 2
}
}
},
});
</script>
enter image description here
You can use the tooltip callback for this:
const options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw *100}`)
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>
Thanks for the answer, how can I use it if I want to write different values instead of multiplying by 100.
label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw *100}`)

How can I change the label name when you hover your data in Chart.js?

I have this line of code using a chart.js in Laravel App
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
var ctx = document.getElementById("array_crawl_source_gap").getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Google Analytics", "Google Analytics", "Web", "Web"],
datasets: [{
data: [ {{ $array_crawl_source_gap[0] }}, {{ $array_crawl_source_gap[1] }},
{{ $array_crawl_source_gap[2] }}, {{ $array_crawl_source_gap[3] }} ],
backgroundColor: [
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
]
}]
},
options: {
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
}
}],
xAxes: [{
ticks: {
beginAtZero:true,
stepSize: 100
}
}],
}
}
});
Here is the output of my code.
Expected output:
Base on my codes how can I able to make only one Google Analytics and Web in labels? And is it possible to change the labels when you hover the data as the picture below? Any idea/thoughts how can I fix this. Thank you in advance.
Custom tooltip position:
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
Added tooltipText for custom tooltip titles, also callbacks to display those titles and labels. Y-axis labels have offset.
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Google Analytics", "", "Web", ""],
tooltipText: ["Wild Quess", "Very Analytical", "Fine Prediction", "Bob's opinion"],
datasets: [{
data: [ 250 , 260 , 270 , 280 ],
backgroundColor: [
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
]
}]
},
options: {
responsive: false,
legend: { display: false },
tooltips: {
enabled: true,
displayColors: false,
yPadding: 10,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
titleFontColor: 'rgb(50, 100, 50)',
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
callbacks: {
title: function(tooltipItem, data) {
var title = data.tooltipText[tooltipItem[0].index];
return title;
},
label: function(tooltipItem, data) {
return tooltipItem.xLabel+' pages';
}
},
position: 'custom',
},
scales: {
yAxes: [{
ticks: {
type: 'category',
labelOffset: 35,
},
}],
xAxes: [{
ticks: {
beginAtZero:true,
stepSize: 100
}
}],
},
}
});
Manual on tooltip:
https://www.chartjs.org/docs/latest/configuration/tooltip.html
HTML in tooltip:
Chart JS Show HTML in Tooltip

Chart.js data structure for doughnut chart with php

Struggling to get my doughnut chart to display (v2.5.0). It worked when I entered manual data, but now with dynamic data I'm struggling. Setting up the data in a PHP Laravel controller.
I suspect the $viewData setup is incorrect, hence why it's not displaying the chart. It is displaying the chart text though.
PHP:
$labels = array();
$dataset = array();
foreach ($count as $c) {
array_push($dataset, $c->total);
array_push($labels, $c->race);
}
$viewData = array('labels'=>$labels, 'datasets'=> array(
array(
'backgroundColor' => "#3e95cd",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[0]),
array(
'backgroundColor' => "#8e5ea2",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[1]),
array(
'backgroundColor' => "#3e95cd",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[2]),
array(
'backgroundColor' => "#8e5ea2",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[3]),
array(
'backgroundColor' => "#3e95cd",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[4]),
array(
'backgroundColor' => "#8e5ea2",
'hoverBackgroundColor'=> "rgba(62, 149, 205, 0.57)",
'data'=> $dataset[5])
));
return (json_encode($viewData));
Javascript:
$(document).on('ready', function() {
$.ajax({
url: './dashboard/overallmetrics',
data: {_token: "{!!csrf_token()!!}"},
dataType: 'json',
method: 'post'
}).done(function (data) {
console.log('Success!', data);
var ctx = document.getElementById("myChart").getContext("2d");
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
responsive: true,
title: {
display: true,
text: 'Athlete count per ethnicity'
}
}
});
});
JSON
{"labels":["asian","black","colored","indian","other","white"],"datasets":[{"backgroundColor":"#3e95cd","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":26},{"backgroundColor":"#8e5ea2","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":27},{"backgroundColor":"#3e95cd","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":3},{"backgroundColor":"#8e5ea2","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":27},{"backgroundColor":"#3e95cd","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":30},{"backgroundColor":"#8e5ea2","hoverBackgroundColor":"rgba(62, 149, 205, 0.57)","data":31}]}

How to make two y-axis graph appear together using my own phpMyadmin database

i'm relatively new to the website and seeking help for the current project i'm doing which is to show two line graphs appear on the y-axis with a constant x-axis. My code looks something like this for the php:
<?php
header('Content-Type: application/json');
$lala = 'gender_male';
$lele = 'gender_female';
$con = mysqli_connect("127.0.0.1","root","imnoob","csv_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$data_points1 = array();
$result = mysqli_query($con, "SELECT * FROM centurysq2012");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['weekid'] , "y" => $row[$lala]);
$point1 = array("x" => $row['weekid'], "y" => $row[$lele]);
array_push($data_points, $point);
array_push($data_points1, $point1);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
echo json_encode($data_points1, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
which will be put into my html file codes which is something like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).onload(function () {
$.getJSON("doubleline.php", function (point, point1) {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title: {
text: "Footfall by Gender"
},
animationEnabled: true,
axisX: {
valueFormatString: ""
//intervalType: "month"
},
toolTip: {
shared: true
},
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Male",
markerType: "square",
color: "#F08080",
dataPoints: point
},
{
type: "line",
showInLegend: true,
name: "Female",
color: "#20B2AA",
lineThickness: 2,
dataPoints: point1
}],
legend: {
cursor: "pointer",
itemclick: function (e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width:400px; height:100%;"></div>
</body>
</html>
Sorry for my codes being messy or the question being a lousy one as i'm still currently a student. Thank you for all your help in advance!
$.getJson method will only return your PHP output result as a variable, you can't assign it into point1, point2. So for your PHP coding, you probably need to do the below amendments:
$result = array($data_points,$data_points1);
echo json_encode($result, JSON_NUMERIC_CHECK);
instead of echo json_encode($data_points, JSON_NUMERIC_CHECK);
echo json_encode($data_points1, JSON_NUMERIC_CHECK);
In order to show two lines you will need to make 2 sets of data inside your data-> for eg: data:[{SET1}, {SET2}], you may refer the HTML codes below, this will show you 2 lines on your chart:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Earthquakes - per month"
},
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
dataPoints: [
{ x: new Date(2012, 00, 1), y: 450 },
{ x: new Date(2012, 01, 1), y: 414},
{ x: new Date(2012, 02, 1), y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle"},
{ x: new Date(2012, 03, 1), y: 460 },
{ x: new Date(2012, 04, 1), y: 450 },
{ x: new Date(2012, 05, 1), y: 500 },
{ x: new Date(2012, 06, 1), y: 480 },
{ x: new Date(2012, 07, 1), y: 480 },
{ x: new Date(2012, 08, 1), y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross"},
{ x: new Date(2012, 09, 1), y: 500 },
{ x: new Date(2012, 10, 1), y: 480 },
{ x: new Date(2012, 11, 1), y: 510 }
]
},
{
type: "line",
dataPoints: [
{ x: new Date(2012, 00, 1), y: 420 },
{ x: new Date(2012, 01, 1), y: 404},
{ x: new Date(2012, 02, 1), y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle"},
{ x: new Date(2012, 03, 1), y: 400 },
{ x: new Date(2012, 04, 1), y: 400 },
{ x: new Date(2012, 05, 1), y: 500 },
{ x: new Date(2012, 06, 1), y: 450 },
{ x: new Date(2012, 07, 1), y: 490 },
{ x: new Date(2012, 08, 1), y: 415 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross"},
{ x: new Date(2012, 09, 1), y: 490 },
{ x: new Date(2012, 10, 1), y: 480 },
{ x: new Date(2012, 11, 1), y: 510 }
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
your chart will look like this:
2 lines chart
for your case, maybe something like this:
$(document).onload(function () {
$.getJSON("doubleline.php", function (result) {
var point1 = result[0];
var point2 = result[1];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title: {
text: "Footfall by Gender"
},
animationEnabled: true,
axisX: {
valueFormatString: ""
//intervalType: "month"
},
toolTip: {
shared: true
},
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Male",
markerType: "square",
color: "#F08080",
dataPoints: point
},
{
type: "line",
showInLegend: true,
name: "Female",
color: "#20B2AA",
lineThickness: 2,
dataPoints: point1
}],
legend: {
cursor: "pointer",
itemclick: function (e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
});
});

When rendering Chart by Ajax Uncaught TypeError: Cannot read property 'getTime' of undefined

When I attempt to render the chart with data passed back form ajax, I receive the error, "Uncaught TypeError: Cannot read property 'getTime' of undefined".
$.ajax({
type : 'POST',
url : 'admin-controllers/chart-contorller.php',
dataType : 'json',
encode : true
})
.done(function(data) {
alert('contorller');
if ( success) {
var dataPoints = data.graphData;
console.log(dataPoints);
var chart = new CanvasJS.Chart("timeToSetChart", {
title:{
text: "User Time to initialy set DNS",
fontSize: 20,
},
axisX:{
labelFontSize: 12
},
axisY: {
title: "Number of users",
titleFontSize: 14,
labelFontSize: 12
},
data: [{
type : 'column',
dataPoints: data.graphData
}]
});
chart.render();
}
my string data.graphData comes back as:
[{x: 10, y: 0, label: "1hours"},{x: 20, y: 0, label: "2hours"},{x: 30, y: 16, label: "6hours"},{x: 40, y: 0, label: "12hours"},{x: 50, y: 0, label: "24hours"},{x: 60, y: 0, label: "2days"},{x: 70, y: 0, label: "3days"},{x: 80, y: 0, label: "4days"},{x: 90, y: 0, label: "5days"},{x: 100, y: 0, label: "6days"},{x: 110, y: 0, label: "7days"},{x: 120, y: 3, label: "8plusdays"},]
Which when I paste it into the dataPoints variable it works fine.

Categories