Pass a textfield value from php to javascript - 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>

Related

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

Updating jqplot Pie Chart via JS not working

I am trying to update jqplot PieChart via JS since yesterday and I am not having any breakthrough with this. I have searched online and cant seem to get any solution work
The chart data is saved in session and this session is continuously being updated by the application.
This is what the JSON looks like
[ ['Take home pay', 44228.33], ['Tax', 8771.67], ['Super', 4162.5 ], ['Regular expenses', 0 ], ['Unallocated', 44228.33], ['Testing', 8000] ]
The chart loads fine when the user navigates to the page for the first time.
This is the DIV where the chart loads
<div id="savings_expense" class="jqplot-target"></div>
This is the jqplot JS when the page loads which works fine
$(document).ready(function () {
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
});
This is the button that user clicks to update the chart.
<li onclick="updateGraph()">YOUR TAKE-HOME PAY</li>
I have tried two ways to update the PieChart
Solution 1
In this solution I get the error Uncaught TypeError: Cannot read property 'replot' of undefined.
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
function renderGraph() {
plot1.replot({
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
});
}
function updateGraph() {
alert('updateGraph');
var newVal = <?php echo $_SESSION['chart_data'] ?>;
storedData.push(newVal);
renderGraph();
}
Solution 2
In this solution the pie chart goes blank but the legends stay
var storedData = <?php echo $_SESSION['SMP']['chart_data'] ?>;
var plot1;
function renderGraph() {
if ( plot1) {
plot1.destroy();
}
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense',[storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
}
I will really appreciate any help here. Please do not share any links as I have gone through about every solution I could find on StackOverflow and on net
You have to keep on document.ready code as it is and then add function updateGraph outside document.ready (keep all variable at global level). Also modify updateGraph, here you need to call .replot() on plot1 variable as you are only changing data and not other setting.
put id to li like this : <li id="updateGraph">YOUR TAKE-HOME PAY</li>
See below code :
// declare variable outside document.ready
var plot1;
var storedData;
$(document).ready(function () {
storedData = <?php echo $_SESSION['chart_data'] ?>;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
$('#updateGraph').click(function(){updateGraph();});
});
function updateGraph() {
var newVal = <?php echo $_SESSION['chart_data'] ?>;
plot1.destroy();
plot1.series[0].data = newVal;
plot1.replot(true);
}

Dojo Chart issues in naming label of X-axis name

I am new to dojo chart. I am trying to create a stacked column chart using dojo . I am trying to show bar chart with line chart using dojo chart.Chart is appear. But here is my problem is how can i write my x-axis label name which comes from my database.I want to naming each bar's name on X-axis. My actual values comes from database. I searches from all stack overflow suggestion,dojo guides and from others but i could not found any proper solution.So i request to you please help me where my code is wrong.So here i can rectify me for futures.
Here is my code index.php
<?php
include "connection.php";
$array = array();
$array1 = array();
$array2 =array();
$query1 = "SELECT name,rate1,rate2 FROM TEST";
$result = mysql_query($query1) or die ('Could not find Projects');
while ($rows = mysql_fetch_array($result)){
$array1[]=$rows['name'];
$array1[]=$rows['rate1'];
$array2[]=$rows['rate2'];
}
print_r($array1);
print_r (json_encode($array1,JSON_NUMERIC_CHECK));
print_r (json_encode($array2,JSON_NUMERIC_CHECK));
<html><head>
<link rel="stylesheet" href="dijit/themes/tundra/tundra.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src='dojo/dojo.js'></script>
<script type="text/javascript">
require(["dojox/charting/Chart",
//"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojox/charting/plot2d/StackedColumns",
"dojox/charting/action2d/Tooltip",
"dojo/ready",
"dojox/charting/widget/SelectableLegend"],
function(Chart, Default, StackedColumns, Tooltip, ready, SelectableLegend) {
ready(function() {
var chart1 = new Chart("chart1");
chart1.addPlot("stackedColumnsPlot", {
type: StackedColumns,
lines: true,
areas: true,
markers: true,
tension: "S"
});
chart1.addPlot("linesPlot", {
type: Lines,
markers: true,
stroke: {
width: 2
},
tension: 2
});
chart1.addAxis("x");
chart1.addAxis("y", {
vertical: true
});
chart1.addSeries("Series 1", <?php echo json_encode($array1,JSON_NUMERIC_CHECK); ?>
, {
plot: "stackedColumnsPlot",
stroke: {
color: "blue"
},
fill: "lightblue"
});
chart1.addSeries("Series 2", <?php echo json_encode($array2,JSON_NUMERIC_CHECK); ?>, {
plot: "stackedColumnsPlot",
stroke: {
color: "green"
},
fill: "lightgreen"
});
new Tooltip(chart1, "stackedColumnsPlot", {
text: function(chartItem) {
console.debug(chartItem);
return "Value: " + chartItem.run.data[chartItem.index] + "; Stacked Value: " + chartItem.y;
}
});
chart1.render();
new SelectableLegend({
chart: chart1,
horizontal: false
}, "chart1SelectableLegend");
});
});
</script>
This is my code what i am writing for stacked column chart.So suggest me how can i write label name of x-axis in my chart which comes from my database.
Add a label to the x axis:
Here are a few examples:
Use title property for one label for the entire axis.
chart.addAxis("x", {
min: 0, max: 100,
fontColor: "blue",
vertical: true,
fixLower: "major", fixUpper: "major",
title: "X axis title",
titleFont: "bold bold bold 12pt Arial,sans-serif",
titleOrientation: "axis"
});
For labels on each tick mark on the x axis:
var xAxisLabels = [{text: "Today",value: 1},{text: "-1",value: 2},{text: "-2",value: 3},{text: "-3",value: 4},{text: "-4",value: 5},{text: "-5",value: 6},{text: "-6",value: 7},{text: "WK-1",value: 8},{text: "WK-2",value: 9},{text: "WK-3",value: 10},{text: "WK-4",value: 11}];
chart.addAxis("x", {
labels: xAxisLabels,
fontColor: "blue",
majorTicks:true,
majorTickStep:1,
minorTicks:false,
max: 11
});
Not sure about the database part

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