Problems with the x axis in morris.js - javascript

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

Related

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

Converting PHP array into JQuery data

I have encountered a little of a problem while trying to convert PHP array into jQuery. I have read a lot of threads on forum and I still cannot figure out what's wrong.
My PHP code that's basically for adding last 7 dates into array and assigning "a" and "b" to same value just for tests
$dni = array();
for($i =7; $i>0; $i--){
$dzien = date("Y-m-d", strtotime($i." day"));
$d->y = $dzien;
$chart = mysql_query("SELECT COUNT(*) FROM kolejka WHERE data LIKE '$dzien' AND odbyta = '0'", $link);
while($c = mysql_fetch_array($chart, MYSQL_ASSOC))
{
$xdi = $c['COUNT(*)'];
}
$d->a = $xdi;
$d->b = $xdi;
$dni[] = $d;
}
$data = json_encode($dni);
My jQuery code that's supposed to generate a chart:
var ar = <?php echo json_encode($data); ?>;
alert(ar);
Morris.Bar({
element: 'pacjenci-chart',
data: ar,
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['New', 'Old'],
barColors: ['#33414E', '#1caf9a'],
gridTextSize: '10px',
hideHover: true,
resize: true,
gridLineColor: '#E5E5E5'
});
If I put into "data" a non-dynamic content like:
data: [
{ y: 'Oct 10', a: 75, b: 35 },
{ y: 'Oct 11', a: 64, b: 26 },
{ y: 'Oct 12', a: 78, b: 39 },
{ y: 'Oct 13', a: 82, b: 34 },
{ y: 'Oct 14', a: 86, b: 39 },
{ y: 'Oct 15', a: 94, b: 40 },
{ y: 'Oct 16', a: 96, b: 41 }
],
It works just fine.
An output of
var ar = <?php echo json_encode($data) ?>;
is
var ar = "[{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"}]";
arent you doing json-encode twice here?
$data = json_encode($dni);
var ar = <?php echo json_encode($data); ?>;
Get rid of one of these and it should just work like this.
It is slightly obvious because of all the extra escape's to encode a json string again it will be converted to a string :-). Just echo the $data variable.
You encoded the array twice - first in PHP then in jQuery.
var ar = <?php echo json_encode($data); ?>;
remove json_encode()
var ar = <?php echo $data; ?>;

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