Google Column chart mysql php is not display - javascript

As I have written some of Javascript and MySQL for populate dynamic data for google chart, I have got few chart working but one chart is baffled me, I knew it should be working but I feel that I'm missing something, as it doesn't show at all.
error code displayed
Uncaught (in promise) ReferenceError: Amazon is not defined
at columnCharttotal (Dashboard.php:144)
at
Here is Javascript code
<script type="text/javascript">
//begin columns chart
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(columnCharttotal);
function columnCharttotal() {
var data = google.visualization.arrayToDataTable([
["marketplace_name", "total_amount", {role: "style"}],
<?php
while (($rowResult = mysqli_fetch_array($totalresultchart, MYSQLI_ASSOC)) != NULL) {
?>
[ <?php echo $rowResult["marketplace_name"]; ?>, <?php echo $rowResult["total_amount"]; ?>, "blue"]
<?php
}
mysqli_free_result($totalresultchart);
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"},
2]);
var options = {
title: "Total of all Europe sold",
height: 400,
bar: {groupWidth: "95%"},
legend: {position: "none"},
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
//end of column chart
</script>
here is an HTML code
<div class="col-sm-4">
<div id="columnchart_values" style="width:100%"></div>
<br>
</div>
As Chrome Developer tools displayed show data on console

Look at this line;
[ <?php echo $rowResult["marketplace_name"]; ?>, <?php echo $rowResult["total_amount"]; ?>, "blue"]
Its outputting
[ Amazon.co.uk , 1231231, "Blue" ]
When it should output:
[ "Amazon.co.uk" , 1231231, "Blue" ]
Therefore; change the line too:
[ "<?php echo $rowResult["marketplace_name"]; ?>", <?php echo $rowResult["total_amount"]; ?>, "blue"]

Related

PHP not showing within the data part of a chart.js

I have managed to get both PHP and JavaScript code working on the same page. In the top of the page on the left you can see that my figures from my php tables are being pulled out correctly however, the moment I go to paste the php code inside of where the table 'data' needs to be kept it doesn't work even though surrounded in php tags.
<?php
$conn = mysqli_connect("localhost", "x", "y", "z");
$query = "SELECT * FROM `checkPointMod`";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['mod1']."<br>";
echo $row['mod2']."<br>";
echo $row['mod3']."<br>";
echo $row['mod4']."<br>";
echo $row['mod5']."<br>";
echo $row['mod6']."<br>";
}
$conn -> close();
?>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
</head>
<body style="background-color: lightgrey;">
<div class="col-md-4 text-center">Third of Page - Middle section with progress bar
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [<?php echo $row['mod1']?>, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</html>
Update: - I've gone to inspect element to see what the output is and it's seen here, I also placed mod2 in to see if 6 would appear...
I missed that $row only exists inside that while loop.
Replace your while loop with this:
$rows = [];
while ($row = $result -> fetch_assoc()) $rows[] = $row;
Down in your Javascript code, add this at the top:
const data = <?= json_encode($rows, JSON_NUMERIC_CHECK) ?>;
You should end up with this in your page source:
const data = [{ "checkPID": 6, "mod1": 0, "mod2": 6, "mod3": 0, "mod4": 3, "mod5": 2, "mod6": 1, "idUsers": 1 }];
Now you can do this in your Chart setup:
data: Object.keys(data[0]).filter(key => key.startsWith("mod")).map(key => data[0][key]),

Problems with the x axis in morris.js

I am working on a website. On one of the pages I draw a line chart with morris.js . But the x axis looks like this
It places 190 before the day number so I want it do look like Day 1 , Day 2 ...
Here is my source code for the chart:
var DataForChart1 = [
{x:'1' , a: <?php echo h($day1); ?> },
{x:'2' , a: <?php echo h($day2); ?> },
{x:'3' , a: <?php echo h($day3); ?> },
{x:'4' , a: <?php echo h($day4); ?> },
{x:'5' , a: <?php echo h($day5); ?> },
{x:'6' , a: <?php echo h($day6); ?> },
{x:'7' , a: <?php echo h($day7); ?> },
{x:'8' , a: <?php echo h($day8); ?> },
{x:'9' , a: <?php echo h($day9); ?> },
{x:'10' , a: <?php echo h($day10); ?> }
];
config1 = {
data: DataForChart1,
xkey: 'x',
ykeys: 'a',
xLabelAngle: '70',
labels: 'Кръвно налягане горна граница',
fillOpacity: 0.6,
hideHover: 'auto',
behaveLikeLine: true,
resize: true,
pointFillColors:['#ffffff'],
gridTextSize: 15,
verticalGrid: true,
gridTextColor: '#5cb85c',
pointStrokeColors: ['black'],
padding: 50,
lineColors:['red']
};
config1.element = 'chart1';
Morris.Line(config1);
The reason why x is '1' , '2' ... , '10' is because if i put in front of it something like day then the whole thing would look like this.
If you know a solution to this problem please tell me. Thanks for reading.
Add parseTime: false to your config to disable the date being used.
Despite putting 1, 2, 3 as x, morris.js by default populates x as a date (hence the reason 1901, 1902, 1903, etc is being displayed).
Here's a jsFiddle with the fix

google charts no data (blank page)

i have a web page contain 8 google charts
when i have all data for the charts it work fine
but sometimes there is some charts has no data (2 or 3 out of the 8 )
so i get a blank page cause this charts
how to skip the script of the blank data charts
here is the script of one of them (all the similar script)
<script type="text/javascript">
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif' ],
<? foreach($***THEBlankDATAHERE***->getRows() as $row) {
$DBcostmonth = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', $row[0])
->get();
$test = $DBcostmonth[0]->value; ?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?>, <? echo $test; ?>],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('div1_3'));
chart.draw(data, options);
}
Edited : this data source is from parent view in laravel 4.1 and it is a google analytics data
so some users have access to all data for the charts and some dont have access to data in some charts
Edited2 :
i change the script in the code and i get the page but without any charts the new code is :
<?php if ($tristanweekdata) { ?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif'],
<? foreach($tristanweekdata->getRows() as $row) {
$DBcostweek = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', wtm($row[0]))
->get();
$test = $DBcostweek[0]->value/4.33;
?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?> ,<? echo $test;?> ],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('tristancostweek'));
chart.draw(data, options);
}
<?php } ?>
now i get different error in the console of the browser :
""Uncaught TypeError: Cannot read property 'arrayToDataTable' of undefined""
thanks
i figured the right way to make it work :)
the answer to this question is in the edited2 in the question but there is a 1 change
what you need is to to put the google chart load out the of the script and make it alone like that:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
</script>
then you can put the condition that you want in mine like that :
<?php if ($tristanweekdata) { ?>
<script type="text/javascript">
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif'],
<? foreach($tristanweekdata->getRows() as $row) {
$DBcostweek = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', wtm($row[0]))
->get();
$test = $DBcostweek[0]->value/4.33;
?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?> ,<? echo $test;?> ],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('tristancostweek'));
chart.draw(data, options);
}
</script>
<?php } ?>
then all the charts is working if the user have the right access ;)
Thanks to #WhiteHat for his help

morrisJS Bar chart population using PHP and mysql

I'm struggling with getting data to populate my MorrisJS bar chart using data from my mySQL database. Could anyone assist in getting it to display on my bar chart?
Below is my current code and pages.
<?php
$link = mysql_connect('127.0.0.1', 'root', 'password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('database') or die('Could not select database');
$dataArray=array();
//get data from database
$sql="SELECT * FROM table";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$Version=$row["Version"];
$Live=$row["Live"];
$Preprod=$row["Preprod"];
//add to data areray
$dataArray[$Version]=$count;
}
}
?>
index.php (main page)
div id="morris-bar-chart"></div>
<?php include ('database.php') ?>
<script src="../js/morris-data.js"></script> <----- script on index.php page linking to morris chart page.
morris.js page
Morris.Bar({
element: 'morris-bar-chart',
data: [{
while ($row = mysql_fetch_assoc($result)) {
y:<?=$row['versions']?>,
Live:<?=$row['Live']?>,
PreProd: <?=$row['Preprod']?>
}, {
],
xkey: 'y',
ykeys: ['Live', 'PreProd'],
labels: ['Live', 'PreProd'],
hideHover: 'auto',
resize: true
});
Hope this all makes sense. Thanks in advance.
I think the while is the problem.
Morris expects data line-wise, e.g. { y: '2007', a: 75, b: 65 },
I've adjusted the PHP code part in the morris.js script a bit.
Normally, you can not execute PHP within a JS file. Except, when you added a rule to the server, that JS files should be processed by PHP, too.
The normal way to fetch the data would be an AJAX query to a PHP script, which returns the json_encoded($result). And then add it to Morris with the setData() function.
But this should work, too: generate the JS file by PHP. You could rename the morris-data.js to morris-data.js.php. The file needs <?php header("Content-type: application/javascript"); ?> at the top. And then adjust your <script include to match the new filename.
File morris-data.js.php
<?php header("Content-type: application/javascript"); ?>
Morris.Bar({
element: 'morris-bar-chart',
data: [
<?php
while ($row = mysql_fetch_assoc($result)) {
// output a line like:
// { y: '123', Live: 123, PreProd: 123 },
sprintf(
"{ y: '%s', Live: %s, PreProd: %s },",
$row['version'],
$row['Live'],
$row['Preprod']
);
}
?>
],
xkey: 'y',
ykeys: ['Live', 'PreProd'],
labels: ['Live', 'PreProd'],
hideHover: 'auto',
resize: true
});
that should render something like (see also the bar chart example)
data: [
{ y: '1.2.3', Live: 20, PreProd: 23 },
{ y: '1.2.4', Live: 30, PreProd: 24 },
{ y: '1.2.5', Live: 40, PreProd: 25 },
{ y: '1.2.6', Live: 50, PreProd: 26 }
],
(I'm not sure what the last part in the database.php file is supposed to do.
Maybe you can drop that (the code inside the if($result)). But maybe its for calculations..)

Highcharts column only show one category

I make a chart using Highchart with column type. I working with database mysql
series: [<?php while ($c1=mysql_fetch_array($qc1)){ ?>
{
name: '<?php echo $c1[0]; ?>',
data: [<?php echo $c1[1]; ?>]
},
<?php } ?>
]
I want to numbering xAxes from 1-11
xAxis: {
categories: ['1','2','3','4','5','6','7','8','9','10','11']
},
But it only show 1.
It's caused by creating multiple series, so there are two options:
1) Create one series instead:
series: [
data: [<?php while ($c1=mysql_fetch_array($qc1)){ ?>
{
name: '<?php echo $c1[0]; ?>',
y: [<?php echo $c1[1]; ?>]
},
<?php } ?>
]
}
2) Or for each of the points set x:
series: [
<?php
$index = 0;
while ($c1=mysql_fetch_array($qc1)){
$index++;
?>
{
name: '<?php echo $c1[0]; ?>',
data: [<?php echo $index.','.$c1[1]; ?>]
},
<?php
}
?>
]
Note: Second solution may require to set plotOptions.series.grouping = false. Otherwise Highcharts will make space in each category for all of the series.

Categories

Resources