Trying to pass a php variable into js - javascript

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>

Related

Pass a textfield value from php to javascript

I created a field to choose a label for a highchart on wordpress backoffice like this:
public static function sm_register_chart() {
$charts = array();
if( function_exists( 'wdt_get_all_charts_nonpaged')){
foreach( wdt_get_all_charts_nonpaged() as $table ){
$charts[$table['id']] = $table['title'];
}
}
$captions = array();
$fields = array(
array(
'label' => esc_html( 'Graphic' ),
'description' => esc_html( 'Choose the graphic' ),
'attr' => 'chart',
'type' => 'select',
'options' => $charts,
),
array(
'label' => esc_html( 'Footer label' ),
'description' => esc_html( 'Choose the footer label' ),
'attr' => 'footer_caption',
'type' => 'text',
),
);
And i want to pass whatever is typed in footer_caption to this js that i took from this fiddle: http://jsfiddle.net/abenrob/ur02w4j5/
Highcharts.setOptions({
chart: {
type: 'column',
events: {
load: function () {
var label = this.renderer.label("This text will adjust to chart resizing " +
"and redraws and will be visible on exported images.")
.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: 0 // offset
}), null, 'spacingBox');
}
},
marginBottom: 120
},
legend: {
align: 'center',
verticalAlign: 'bottom',
y: -30
},
So that instead of that var label = this.renderer.label("This text will adjust to chart resizing") i get the value of footer_caption.
I was thinking of something like this:
var labelText = document.querySelectorAll('[footer_caption]').text()
var label = this.renderer.label(labelText)
But it doesn't work and im not able to even get the value i type from footer_caption
You can achieve this by doing the following; you may have to change the identifier for footer_caption depending on your own code;
<script type="text/javascript">
var footer_caption = <?= json_encode($arr['footer_caption']); ?>;
</script>
And then reference the variable where it is needed in the javascript code.
Using json_encode ensures that illegal characters etc are correctly handled. The code above makes use of PHP quick tags more reference can be found here.
you can use json_encode to do this
<script>
var footer_caption = <?php echo json_encode($fields); ?>;
</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);
}

Queried Data as Datapoints on Chart.js

I am trying to plot chart using Chart.JS based on my data from database. Here number of Labels and their values will come directly from the query result. Here is my code:
<script type="text/javascript">
window.onload = function () {
<?php
function getValsOfCategoryLabels(){
$yValsWithLabels = "";
......
// some codes to make query on db and get result in $queryResult variable
......
......
foreach($queryResult as $data){
$x0 = $data0['name'];
$total = $data0['total'];
$yValsWithLabels = $yValsWithLabels. "{y: ".$total.", label: \"".$x0."\"}, ";
}
return $yValsWithLabels;
}
?>
var categoryLabelsNdVals = [<?php echo getValsOfCategoryLabels() ?>];
var hourlyCategoryBarChart = new CanvasJS.Chart("columnchartContainer", {
animationEnabled: true,
axisX: {
labelFontSize: 16
},
axisY: {
title: "",
labelFontSize: 13
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 16
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "Name of Category",
dataPoints: categoryLabelsNdVals
}
]
});
hourlyCategoryBarChart.render();
Now for the given datapoints (which is in "{y: Some_Value, label: Some_Name}" format) I am not getting any chart as output, unless I explicitly declare all the y-axis values and label names myself, which fails reflect database info.
What is the right way to accomplish my objective?

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

flot doesn't draw bars chart

I tried with my other two scripts(line chart and pie chart) but the flot doesn't draw the bars chart... can you help me with this...I think the error is in the javascript..
The library:
<script src="js/jquery.flot.min.js"></script>
<script src="js/jquery.flot.pie.min.js"></script>
<script src="js/jquery.flot.stack.js"></script>
<script src="js/jquery.flot.resize.min.js"></script>
Here is the printdata db call:
[["junio",390],["julio",125],["agosto",50]]
Here is the script in graficayear.php:
<?php
include 'includes/configs.php';
$sql = $conn->prepare("SELECT DATE_FORMAT(start, '%M') AS mdate, SUM(honorario) AS total_mes
FROM CITAS WHERE YEAR(current_date) GROUP BY mdate DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$datayear[] = array($row['mdate'],(int) $row['total_mes']);
}
?>
Here is the code in chartyear.php:
<?php include 'graficayear.php'; ?>
<script type='text/javascript' charset='utf-8'>
$(function () {
$.plot(
$("#baryear"),
[{
data : <?php echo json_encode($datayear);?>,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', barWidth: (15*24*60*60*1000), align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
mode: 'time',
tickDecimals: 0,
tickSize: [1,'month'],
autoscaleMargin: 0.001
}
}
);
});
</script>
And the DIV with the ID:
<?php include 'chartyear.php'; ?>
<div id="baryear" style="width: 320px; height: 300px;"></div>
here is how my chart look like until now:
And this is the data I need to show inside of the bars chart:
You need to read the documentation on the expected data formats more carefully. Here you've specified an xAxis of type time but then have given it categories. You have to pick one way or the other.
So, given the format of you json data, here the shortest path to do what you want:
// given your data
var datayear = [["junio",390],["julio",125],["agosto",50]];
// split it into a data array and a ticks array
var data = [], ticks = [];
for (var i = 0; i < datayear.length; i++) {
data.push([i,datayear[i][1]]); // note that the x value is numeric
ticks.push([i,datayear[i][0]]); // and that the x value is matched to a "category"
}
$.plot(
$("#baryear"),
[{
data : data,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
ticks: ticks
}
});
Fiddle here.
Produces:

Categories

Resources