Problem in displaying mutlitple charts using Php mysql - javascript

Im trying to display 2 different pie chart which takes value from php database. but problem is when I do the second pie chart, the first pie chart would not show but will show the second pie chart, means it works 1 at the time.
Where is the error?
1st code for pie chart
?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT Gender, COUNT(Gender) AS totalUser FROM register GROUP By Gender");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result as $row){
array_push($dataPoints, array("x"=> $row->Gender, "y"=> $row->totalUser));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
1 JavaScript for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Gender Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
2nd php code for pie chart
<?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT BasedAt, COUNT(BasedAT) as TotalImmigrant FROM register GROUP By BasedAt");
$handle->execute();
$result1 = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result1 as $row){
array_push($dataPoints, array("x"=> $row->BasedAt, "y"=> $row->TotalImmigrant));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
2nd JS for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer1" style="height: 370px; width: 100%;"></div> <!--Location Chart-->
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

Keep first chart as it is and try use this for second chart
window.onload = function () {
var chart_sec = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart_sec.render();
}

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.

CanvasJS in function only shows one chart (php, js)

function timeDataToPointChart($dataPoints,$title,$xlabel,$ylabel,$chartID) {
?>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function () {
var NameOfChart = "<?php echo $chartID; ?>"
window[NameOfChart] = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "<?php echo $title; ?>"
},
axisX:{
title: "<?php echo $xlabel; ?>",
valueFormatString: "MM/YYYY",
crosshair: {
enabled: true
}
},
axisY: {
title: "<?php echo $ylabel; ?>"
},
data: [
{
type: "line",
xValueType: "dateTime",
dataPoints:
<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}
]
});
window[NameOfChart].render();
function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else{
e.dataSeries.visible = true;
}
window[NameOfChart].render();
}
}
</script>
<div id="chartContainer" style="height: 370px; width: 650px;"></div>
<?php
}
?>
I use this PHP function to generate my canvas chart. This works well, but if I call the function twice on a page, only one chart is shown.
Console shows the following error, but I don't understand what's wrong.
CanvasJS namespace already exists. If you are loading both chart and
stockchart scripts, just load stockchart alone as it includes all
chart features.
Thank you for your help.
As described from canvasJs, i've implemented the code accordingly in my Laravel App like below
#foreach($records as $record)
<div id="chartContainer{{$record->employeeRequisitionId}}" style="height: 270px; width: 100%;"></div>
#endforeach
#push('after_scripts')
<script>
window.onload = function () {
#foreach($records as $record)
const chart{{$record->employeeRequisitionId}} = new CanvasJS.Chart ( "chartContainer{{$record->employeeRequisitionId}}", {
animationEnabled: true,
theme: "light2",
title: {
text: "Requisition According Fiscal Year"
},
axisY: {
suffix: "%",
scaleBreaks: {
autoCalculate: false
}
},
data: [{
type: "column",
yValueFormatString: "#,##0\"%\"",
indexLabel: "{y}",
indexLabelPlacement: "inside",
indexLabelFontColor: "white",
dataPoints: {!! formatRequisitionAccordingFiscalYearData($record) !!}
}]
} );
#endforeach
#foreach($records as $record)
chart{{$record->employeeRequisitionId}}.render ();
#endforeach
}
</script>
#endpush

Highcharts loaded via ajax, issue to dynamically create yAxis

I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body>
<!-- FIELDS -->
<div id="fields">
<form method="post" action="">
<select id="f" name="f[]" multiple>
<option value="rss1" select>1RSS(dB)</option>
<option value="rss2">2RSS(dB)</option>
<option value="rqly">RQly(%)</option>
<option value="rsnr">RSNR(dB)</option>
</select>
</form>
</div>
<!-- GRAPH -->
<div id="graph">No selection</div>
<script>
var updateChart = function(json) {
// console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: []
}
options.series = json;
var chart = new Highcharts.Chart(options);
// update yaxis
for (i=0; i<json.length; i++) {
if(i==0) {
// it seems that a yAxis already exist when graph is initialized. Did not find a smarter way to destroy it...
chart.yAxis[0].update({ title: { text: json[i].name }});
} else {
chart.addAxis({ title: { text: json[i].name } });
}
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
});
});
</script>
</body>
</html>
Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();
// Include config file
require_once "config.php";
$jsonObject = array();
$yaxis = 0;
foreach($_POST["f"] as $v) {
$data = array();
$sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
$result = $link->query($sql);
while($row = $result->fetch_row()) {
$data[] = $row[0];
}
$jsonObject[] = array(
"name" => $v,
"data" => $data,
"yAxis"=>$yaxis
);
$yaxis++;
}
$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;
// Close connection
mysqli_close($link);
?>
When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
at Object.a.error (highcharts.src.js:498)
at highcharts.src.js:32669
at Array.forEach (<anonymous>)
at r.<anonymous> (highcharts.src.js:32621)
at a.fireEvent (highcharts.src.js:2635)
at r.bindAxes (highcharts.src.js:32618)
at r.init (highcharts.src.js:32482)
at a.Chart.initSeries (highcharts.src.js:26913)
at highcharts.src.js:28765
at Array.forEach (<anonymous>)
I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.
I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
var updateChart = function(json) {
//console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
yAxis:[],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [],
tooltip: { shared: true }
}
var chart = new Highcharts.Chart(options);
// update axis and series
for (i=0; i<json.length; i++) {
// add axis
chart.addAxis({ title: { text: json[i].name } });
// add serie
var a = chart.series.length;
var seriesOptions = {
name: json[i].name,
data: json[i].data,
yAxis: a
}
chart.addSeries(seriesOptions,true);
chart.options.series.push(seriesOptions);
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
//return false;
});
});

Reading MySQL data into highstocks

So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));

Two google bar charts not working in one page

I am not able to show two bar charts in one page. I have tried both ways, implementing these in two different <script> sections in and in one <script> section also. If one is shown if I make changes to <div> id, another is not shown and vice versa but both of them not shows at one time. I have also tried with visualization version change. When I see page source, there I see all the data for both graphs, but only graph is not created. What might be the problem. I have tried a lot, but not able to debug, in last I am here. Below is my code.
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new
google.charts.Bar(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new
google.charts.Bar(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>
And my both arrays become like:
$log_book_discrepancy is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 30
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => OIL TANKER
[fuel_hsfo] => 60
[fuel_lsfo] => 40
[fuel_mgo] => 45
)
)
And $bunker_found array is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 10
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => CHEMICAL TANKER
[fuel_hsfo] => 50
[fuel_lsfo] => 40
[fuel_mgo] => 55
)
)
This is solution without PHP with the given data, first chart with option: "isStacked: true":
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 30, 40, 40],
['OIL TANKER', 60, 40, 45]
]);
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 10, 40, 40],
['CHEMICAL TANKER', 50, 40, 55]
]);
var options1 = {
title: 'Log Book Discrepancy',
chartArea: {width: '50%'},
isStacked: true,
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var options2 = {
title: 'Bunkers Found',
chartArea: {width: '50%'},
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
https://jsfiddle.net/mblenton/pmeh4hr9/2/
or with MaterialChart:
https://jsfiddle.net/mblenton/gp12p37w/2/
Try this:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {packages: ['corechart', 'bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>

Categories

Resources