google charts no data (blank page) - javascript

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

Related

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 Column chart mysql php is not display

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"]

HighChart Line Graph value from database

I want to draw one page with HighChart. I took data from database. I wrote it with json_encode. I can see what my $xxx has value. Its json format. But my graph is not working. I think var data = <?php echo json_encode($xxx); ?> doesnt work and return valur. Where do I mistake?
Here is my php code for database value:
<?php
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$no = 1;
$total_deger=count($data);
foreach($data as $dat)
{
$xxx ="[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
if($no < $total_deger)
{
echo ",";
}
echo json_encode($xxx);
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
?>
And here is my highchart script:
<script>
$(function () {
var data = <?php echo $xxx; ?>;
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: [data]
}]
});
});
</script>
Edit: I edited json format. When I write just echo. Its just see one value.
Edit2: I have 9 value. My output is:
,,,,,,,,[Date.UTC(2016,11,15,10,28,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,27,00),17]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,33,00),93]
[Date.UTC(2016,11,15,18,33,00),34]
[Date.UTC(2016,11,15,18,34,00),34]
But when ı read docs for highchart my value must be
([
[Date.UTC(2016,11,15,10,28,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,27,00),17],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,33,00),93],
[Date.UTC(2016,11,15,18,33,00),34],
[Date.UTC(2016,11,15,18,34,00),34]
]);
Try wrapping it in quotes
var data = "<?php echo json_encode($xxx); ?>"
You should see this as an error in the console
Also you arent concatenating correctly. This means every time the loop runs you are overwriting the last entry stored in $xxx
$xxx = "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
should be
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
Finally, change your loop to work like this
$xxx = '';
foreach($data as $dat){
// if not a blank string i.e. something added, add a comma to the end read for the next concatenation
if($xxx != '') $xxx .= ",";
// concatenate
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
}
// if not blank string, echo
if($xxx != ''){
echo json_encode($xxx);
}

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