Converting PHP array into JQuery data - javascript

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; ?>;

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

Trying to pass a php variable into js

I have the $attr array that contains the id and footer caption of each graph (highcharts) in a post. When i print_r the array it groups the id and footer_caption correctly and in the right order as they are in the post. For eg in the current post im working at i have 3 graphs and this is what's inside $attr:
Array
(
[chart] => 23
[footer_caption] => footer test
)
Array
(
[chart] => 22
[footer_caption] => another test
)
Array
(
[chart] => 24
[footer_caption] => And another test
)
I'm passing $attr['footer_caption] to javascript like this:
<script>
var captionLabel = "<?php echo $attr['footer_caption']; ?>";
console.log(captionLabel);
</script>
And its working fine. Then the problem happens when i use captionLabel on te js file. I tried using a for loop but with no luck. If i console.log captionLabel in the js file, it shows the footer caption of the last graph 3 times. This is the highcharts.js where im using captionLabel:
Highcharts.setOptions({
credits: {
enabled: false
},
chart: {
type: 'column',
events: {
load: function () {
var label = this.renderer.label(captionLabel)
.css({
width: '400px',
fontSize: '9px'
})
.attr({
'r': 2,
'padding': 5
})
.add();
label.align(Highcharts.extend(label.getBBox(), {
align: 'center',
x: 0, // offset
verticalAlign: 'bottom',
y: 20 // offset
}), null, 'spacingBox');
}
},
marginBottom: 120
},
legend: {
align: 'center',
verticalAlign: 'bottom',
y: -30
},
My question is how can i pass the right footer_caption string to each graph in this js? Because right now every footer label is getting the last value. All the 3 graphs get the footer caption "And another test" in this post.
Use json_encode()
<?php
$labels = [
[
['chart'] => 23,
['footer_caption'] => 'footer test 1'
],[
['chart'] => 24,
['footer_caption'] => 'footer test 2'
],[
['chart'] => 25,
['footer_caption'] => 'footer test 3 '
]
];
?>
<script>
var captionLabels = "<?php echo json_encode($labels); ?>";
console.log(captionLabels);
var label;
//access each one like this
captionLabels.forEach(function(label) {
label = this.renderer.label(label.footer_caption);
//graph code.
});
</script>
I think you should generate the array of footer_caption text and send it to javascript as a JSON string.
PHP code:
$array = new array();
foreach ($attr as $value) {
array_push($array, $value['footer_caption']);
}
$captionLabel = json_encode($array);
JS code:
<script>
var captionLabel = JSON.parse("<?php echo $captionLabel; ?>");
console.log(captionLabel);
</script>
captionLabel has to be an array, otherwise it will only hold the last value assigned to it. You should also use an array for all the $attr values and then use json_encode when outputting itto the JavaScript.
<?php
$attr = [
['chart' => '23', 'footer_caption' => 'footer test'],
['chart' => '22', 'footer_caption' => 'another test'],
['chart' => '24', 'footer_caption' => 'And another test']
];
?>
<script>
var captionLabel = <?= json_encode($attr) ?>;
</script>

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);
}

How to correctly format a PHP foreach loop?

I have a PHP PDO query, it selects the year, month and day from the database. It also counts the number of rows that each day has:
SELECT
dateYear, dateMonth, dateDay,
count(dateDay) AS count_days
FROM just_ink
WHERE dateMonth = :month AND dateYear = :year AND deleted = 0
GROUP BY dateYear, dateMonth, dateDay
When echoing the results:
foreach ($result as $subResult) {
foreach ($subResult as $row) {
$year = $row['dateYear'];
$month = $row['dateMonth'];
$day = $row['dateDay'];
$count = $row['count_days'];
echo $month . " " . $day . " " . $year . " " . $count . " lines, ";
}
}
This returns a value like:
June 7 2016 3 lines, June 8 2016 1 lines,
This means, June 7th has 3 forms and June 8th has 1 form.
Now for the formatting, I am using Highcharts basic line chart. The data needs to be formatted in this way:
<script>
$(function () {
$('#container').highcharts({
title: {
text: 'Monthly New Forms',
x: -20 //center
},
xAxis: {
title: {
text: 'Day of the Month'
},
categories: [
'1', '2', '3', '4', '5',
'6', '7', '8', '9', '10',
'11', '12', '13', '14', '15',
'16', '17', '18', '19', '20',
'21', '22', '23', '24', '25',
'26', '27', '28', '29', '30',
'31'
]
},
yAxis: {
title: {
text: 'Month of June'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Number of New Forms Per Day',
data: [1, 2, 3, 4, 5, 6]
}]
});
});
</script>
Where the categories are the x-axis titles, and the series data is the frequency of each day. So If I want to represent
June 7 2016 3 lines, June 8 2016 1 lines,
The series data would need to look like
0, 0, 0, 0, 0, 0, 3, 1, 0, etc.
Any ideas?
First create an array with elements for every day of the month:
$counts = array_fill(1, 31, 0);
Then in your loop, fill in the entry for the day:
foreach ($subresult as $row) {
$day = $row['dateDay'];
$counts[$day] = $row['count_days'];
}
$counts = array_values($counts); // because json_encode treats it as an object if indexes don't start at 0
echo json_encode($counts);
I'm not sure why you're selecting dateYear and dateMonth, since those are the inputs to the query. You don't need to set those variables in the loop, since they'll always be the same thing.
$highchartdata = []
foreach ($subResult as $row) {
$highchartdata[$row['dateDay']] = $row['count_days'];
}
echo json_encode($highchartdata);
get the above json data from server
obj = JSON.parse(data);// parse the json data
for (i = 1; i <=31; i++) {
if(!obj[i]) // if ith key is not defined make it 0
obj[i]=0;
}
console.log(obj);

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