Morris.js Not showing any chart - javascript

i'm trying to make a morris.js line chart which displays the total amount of registered users.
The thing is that it won't show on my index.php.
I have all the javascript and css files imported.
Is there anyone that could give me a hand?
I'm very new to the javascript scene.
So simple answers are welcome haha.
Here is my code:
<?php
$connection = $stmt -> prepare("SELECT * FROM `user`");
$connection -> execute();
$chart_data = '';
while($row = $connection -> fetch(PDO::FETCH_ASSOC)){
$chart_data .= "{ year:'".$row['ID']."'
}";
}
$chart_data = substr($chart_data, 0, -2);
?>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script stc="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkeys:'year',
ykeys:['users'],
});
</script>
<div class="container" style="width:900px;">
<h2 allign="center">Data grafiek</h2>
<br><br>
<div id="chart"></div>
</div>

Your Data should be in this format:
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
I have change the library of jQuery. Putting the JS at the end of HTML code
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
$(document).ready(function(){
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkeys:'value',
ykeys:['year'],
labels: ['year']
});
});
</script>
And PHP code Should be not -2 it will be -1
while($row = mysqli_fetch_assoc($result)){
$id=$row['id'];
$val=$row['fname'];
$chart_data .= "{ year:'$id',value:'$val'},";
}
$chart_data = substr($chart_data, 0, -1);
Try this and share your console if you can

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]),

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

php-ajax call for json data and pass that data to jguage js for widget to show that value

here i want to pass ajax called value to the another script(widget script) in same file. i have successfully done ajax call and justgage widget on a single page. i can successfully print the data got from ajax call using php echo. instead showing the values using echo, i want to use that same value for justgage widget to show. here i am sharing my code.
data.php file is here
<?php
$selm=1;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="js/jquery.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/raphael-2.1.4.min.js"></script>
<script src="js/justgage.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
#divDownloadOuter{
width: 55%;
height:50%;
clear: both;
}
</style>
<script type="text/javascript">
$(window).load(function () {
myFunction();
});
</script>
<script>
var d;
function myFunction() {
setInterval(function(){
$.ajax({
url: "datavalues.php?id=1&selm=<?php echo $selm ?>",
success: function(result){
ip = JSON.parse(result);
sr = parseFloat(ip["srno"]);
document.getElementById("demo1").innerHTML = sr;
document.getElementById("demo2").innerHTML = sr;
}
});
}, 2000);
}
</script>
</head>
<body>
<div id="divDownloadOuter">
<div id="jgDownload1"></div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var gD1 = new JustGage({
id: "jgDownload1",
value: 27,
decimals: 2,
min: 0,
max: 100,
valueFontFamily: "Georgia",
valueFontSize: "150px",
valueFontColor: "orange",
label: "%",
labelFontsize:"10px",
labelFontColor:"white",
width: 100,
height: 100,
relativeGaugeSize: true,
gaugeWidthScale: 0.8,
levelColors: [
"#E63454",
"#AC001F",
"#F6AD37",
"#B87200",
"#24A081",
"#007759",
"#026071",
"#015C71"
],
pointer: true,
counter: true,
});
});
</script>
<h3>value using element by id</h3>
<span id="demo1"></span>
<?php echo "<span id=\"demo2\"></span>"; ?>
</body>
</html>
datavalues.php file is here
<?php
//all values for selected meter encoded and retrive from dashboard 2
$con=mysqli_connect("localhost","root","digi","gmbg");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['selm']) ){
$selm=$_GET['selm'];
$res3 = mysqli_query($con ,"SELECT * FROM meterstatus where `mtr_no` LIKE '$selm' and did='kirti' order by srno desc limit 1");
$row3= mysqli_fetch_assoc($res3);
echo json_encode($row3);
}
mysqli_close($con);
?>
Here i can easily show values in my data.php file with "span id" and "php echo" method. but i want to use that value in justgage widget to show. but i cant pass this ajax call data value to the another js(justgage). i have tried all method but its showing "undefined". Is there any solution regarding this?
use refresh function gD1.refresh(40) For example i just used setTimeout instead of ajax .
ajax : add this code in ajax success part
refresh function gD1.refresh(response_data) // response_data is dynamically
var gD1 ='';
document.addEventListener("DOMContentLoaded", function(event) {
gD1 = new JustGage({
id: "jgDownload1",
value: 27,
decimals: 2,
min: 0,
max: 100,
valueFontFamily: "Georgia",
valueFontSize: "150px",
valueFontColor: "orange",
label: "%",
labelFontsize:"10px",
labelFontColor:"white",
width: 100,
height: 100,
relativeGaugeSize: true,
gaugeWidthScale: 0.8,
levelColors: [
"#E63454",
"#AC001F",
"#F6AD37",
"#B87200",
"#24A081",
"#007759",
"#026071",
"#015C71"
],
pointer: true,
counter: true,
});
});
setTimeout(function(){ gD1.refresh(74); },1000);
<script src="//cdn.jsdelivr.net/raphael/2.1.2/raphael-min.js"></script>
<script src="//cdn.jsdelivr.net/justgage/1.0.1/justgage.min.js"></script>
<body>
<div id="divDownloadOuter">
<div id="jgDownload1"></div>
</div>
</body>

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..)

Categories

Resources