JavaScript won't run if it includes jinja but will run otherwise - javascript

Hello I am running into a problem that seems very simple but I can't find any solution online. Basically I am trying to use flask alongside javascript and using jinja templates to communicate between the two. I have an html file and the jinja template is working to fill out the boxes as I expect however anything in between tags that includes jinja will not run. Any help is much appreciated! The different cases are:
#this will run
<script>alert( 'Hello, 1' );</script>
#this won't
<script>alert( {{TableTitle}} );</script>
#I saw a tutorial that did this but it also won't run
{% block javascript %}
<script>alert( {{TableTitle}} );</script>
{% endblock %}
#when I view the source of the loaded page I see that jinja template has worked and get this:
<script>alert( test_data );</script>
#the ultimate goal is to make this run:
{% block javascript %}
<script>
alert('hello inside')
$(document).ready(function () {
alert( 'Hello, 5' );
const config = {
type: 'line',
data: {
labels: [],
datasets: [
{% for line in lines %}
{
label: {{line}},
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [],
fill: false,
}
{% endfor %}
],
},
options: {
responsive: true,
title: {
display: true,
text: {{TableTitle}}
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Magnitude'
}
}]
}
}
};
const context = document.getElementById('canvas').getContext('2d');
const lineChart = new Chart(context, config);
const source = new EventSource("{{url_for('jsplotter')}}");
source.onmessage = function (event) {
const data = JSON.parse(event.data);
if (config.data.labels.length === 20) {
config.data.labels.shift();
config.data.datasets[0].data.shift();
}
config.data.labels.push(data.time);
{%for i in range(lines|length)%}
config.data.datasets[{{i}}].data.push(data.value[{{i}}]);
{%endfor%}
lineChart.update();
}
});
</script>
{% endblock %}
#which gets transformed into:
<script>
alert('hello inside')
$(document).ready(function () {
alert( 'Hello, 5' );
const config = {
type: 'line',
data: {
labels: [],
datasets: [
{
label: 1V0_REF,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [],
fill: false,
}
{
label: 1V35_REF,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [],
fill: false,
}
],
},
options: {
responsive: true,
title: {
display: true,
text: test_data
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Magnitude'
}
}]
}
}
};
const context = document.getElementById('canvas').getContext('2d');
const lineChart = new Chart(context, config);
const source = new EventSource("/jsplotter");
source.onmessage = function (event) {
const data = JSON.parse(event.data);
if (config.data.labels.length === 20) {
config.data.labels.shift();
config.data.datasets[0].data.shift();
}
config.data.labels.push(data.time);
config.data.datasets[0].data.push(data.value[0]);
config.data.datasets[1].data.push(data.value[1]);
lineChart.update();
}
});
</script>

Related

Displaying labels on a Doughnut Chart using Chart.js

I am really stuck at the moment.
Using Chart.js v3.2.1 to display some charts, which were working great.
Then when I attempted use the chartjs-plugin-datalabels plugin to display labels on a Doughnut chart, that chart no longer displays.
I can't see what I've done wrong. I'm in need of help!
Note: There are a lot of questions similar to this on Google and Stackoverflow but most of them are about previous versions, but my work has only approved for me to be working with the lastst version of Chart.JS.
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2"></script>
<canvas id="canvas3-detailed"></canvas>
The link for your Plugin is broken. You need to remove #2 from the end:
https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels
There is also the not defined error because you reference ChartDataLabels which has not been declared. You need to put it in a string:
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: ["ChartDataLabels"],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="canvas3-detailed"></canvas>
I found out that the version of the plugin I used was incorrect. I have now updated and it is displaying with labels!
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [{
label: "slices",
borderWidth: 3,
data: [2, 3, 2, 1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
color: 'white',
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="canvas3-detailed"></canvas>

How do i pass php variable to .js file to create function Chart

i done create my chart but i dont know how to pass it, i already try use ?php but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title
<script src="includes/templates/chart.js"></script>
chart.js
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['08:00'] , //Jamnya
datasets: [{
backgroundColor: 'rgba(85, 212, 226, 0.2)',
borderColor: '#55d4e2',
label: '<?php echo $dtDateChart1; ?>' ,
data: [600],
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Today',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TOTAL ONLINE'
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
}
);
return myChart;
}
in my php file
$out .= ' <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
and this is my variable that i want to pass to my .js
//result chart1
#mssql_free_result($graph_query2);
$dtDateChart1 = $dateTittleChart1;
$convertChart1 = json_encode($datesChart1);
$totalChart1 = json_encode($nMaxChart1);
$labelChart1 = $convertChart1;
i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.
I believe that you cannot pass variables from php to javascript because they are different things and they are executed in different places.
your php code runs on your server and the javascript code in the client's browser so they are not seen.
what you can do is a php script that echos the content of the variable you want and through javascript and fetch or any library that makes requests to make a request to the php file
Try to make hidden input and put your php variable on its value then collect element value by js in your function
I almost do this and it is working well
First in your code php or html
Add input like
<input type='hidden' value='<?php echo $dtDateChart1; ?>' id='dtDateChart1' >
chart.js
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['08:00'] , //Jamnya
datasets: [{
backgroundColor: 'rgba(85, 212, 226, 0.2)',
borderColor: '#55d4e2',
label: document.getElementById("dtDateChart1").value,
data: [600],
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Today',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TOTAL ONLINE'
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
}
);
return myChart;
}
You should not have php code inside js files.
What you can do instead is:
Inside the php file pass the values you need to js variables.
Then, use the global js variables or pass them as parameters to js functions.
Alternatively, instead of including the separate charts.js file, have the contents of charts.js in the php file inside a <script> tag. This way you can have php and js sideways as you did.

How to call js function in php file?

i have a problem when i want to call js function, the chart is not show up, i dont know how to call js function because i need to show my chart
js function
<script type="text/javascript">
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart2 = new Chart(ctx, {
type: 'line',
data: {
labels: $labelChart2, //Jamnya
datasets: [{
backgroundColor: 'rgba(232,72,163,0.2)',
borderColor: '#e848a3',
label: $dtDateChart2,
data: $totalChart2,
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Yesterday',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '$dtDateChart2 '+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
});
</script>
my php
<canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
anyoone have ever meet with this problem ? when i put in global boddy. the function is call for global and always show value that i define null in other class except class for chart
The issue might be in the following line:
data: $totalChart2,
If $totalChart2 is a php variable, js will not be able to read it.
If your js function is in a php file, you will have to use the following at the least:
data: <?php echo $totalChart2 ?>,
Also make sure the echo command prints a valid js array or object.

Chartjs Line Chart showing old data when hovering

I have a line chart that's created using chart.js. Everything works fine on page load, but when toggle the chart and hover to chart's corners, it shows old charts.
Also here is the live webapp that you can see the behavior.
https://www.batchrank.com/
I tried to fix with update(), destroy and clear however non of them worked.
Thanks a lot for the help,
Here is my code;
var ctx = document.getElementById("chartContainer").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
label: "data",
datasets: [
{
label: "Mobile Speed Scores",
data: mobileData,
backgroundColor: ["rgba(255, 99, 132, 0.2)"],
borderColor: ["rgba(255, 99, 132, 1)"],
borderWidth: 1
},
{
label: "Desktop Speed Scores",
data: desktopData,
backgroundColor: ["rgba(49, 67, 129, 0.2)"],
borderColor: ["rgba(49, 67, 129, 1)"],
borderWidth: 1
}
]
},
options: {
responsive: true,
title: {
display: true,
text: inspectUrl
},
scales: {
xAxes: [
{
type: "time",
display: true,
scaleLabel: {
display: true,
labelString: "Date"
}
}
],
yAxes: [
{
scaleLabel: {
display: true,
labelString: "value"
}
}
]
}
}
});
myChart.render();
const removeElements = elms => elms.forEach(el => el.remove());
removeElements(document.querySelectorAll(".progress"));
function toogleDataSeries(e) {
e.dataSeries.visible = !(
typeof e.dataSeries.visible === "undefined" || e.dataSeries.visible
);
myChart.destroy();
myChart.render();
}
}

How to edit my custom tooltips in my line chart using chart.js?

This is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{{ $nDate }}],
datasets: [{
label: 'All Users',
data: [ {{ $nUser }} ],
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 3,
lineTension: 0,
labelFontSize : '16',
}]
},
options: {
tooltips: {
mode: 'index',
intersect: false,
position: 'nearest'
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
type: 'category',
labelOffset: 10,
stepSize:250,
callback: function(value, index) {
if (value !== 0) return value;
}
},
gridLines:{
drawBorder:false
}
}],
xAxes: [{
gridLines: {
display: false,
},
}],
},
plugins:{
datalabels:{
display:false
}
}
}
});
My output
My Expected Output
How can I able to put/edit custom tooltip in my line chart? I just want to get the exact tooltips in the second picture but I don't have any idea how to fix it? Another thing is my $nDateI only want to show four dates like 8,15,22,29 But when I tried to create a new array label with value of this [" ", " "]; my chart crashed.
You can use custom callback function to render with your own choice html tags and colors, Follow the official documentation link for further guidance.
http://www.chartjs.org/docs/latest/configuration/tooltip.html#external-custom-tooltips
options: {
tooltips: {
enabled: false,
custom: function(tooltipModel) {}
}
}

Categories

Resources