Create a google chart from XML data in a Symfony project - javascript

Please I want to know where to put the XML file from where I retrieve data for the chart, in a Symfony project?
I tried to put values directely in the javascript code and that worked, but when I retrieved data from XML to fill the chart, that didn't work and I got this error in the developer console : Failed to load resource
$(document).ready(function(){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var drawChart= setInterval (function drawCharts() {
var xml=new XMLHttpRequest() ;
xml.open("GET", "statFile.xml",true) ;//this is the line that causes the problem
xml.onreadystatechange = function () {
if (xml.readyState == 4) {
var doc=xml.responseXML ;
var root = doc.getElementsByTagName("CHART") ;
////VALUES IN
var paramss= root[0].getElementsByTagName("VALUES_IN");
console.log(paramss) ;
var value_in1=paramss[0].childNodes[1].innerHTML;
var value_in2=paramss[0].childNodes[3].innerHTML;
var value_in3=paramss[0].childNodes[5].innerHTML;
var value_in4=paramss[0].childNodes[7].innerHTML;
var value_in5=paramss[0].childNodes[9].innerHTML;
var value_in6=paramss[0].childNodes[11].innerHTML;
var value_in7=paramss[0].childNodes[13].innerHTML;
var value_in8=paramss[0].childNodes[15].innerHTML;
var value_in9=paramss[0].childNodes[17].innerHTML;
var value_in10=paramss[0].childNodes[19].innerHTML;
var value_in11=paramss[0].childNodes[21].innerHTML;
var value_in12=paramss[0].childNodes[23].innerHTML;
////VALUES OUT
var paramsx= root3[0].getElementsByTagName("VALUES_OUT");
console.log(paramsx) ;
var value_out1=paramsx[0].childNodes[1].innerHTML;
var value_out2=paramsx[0].childNodes[3].innerHTML;
var value_out3=paramsx[0].childNodes[5].innerHTML;
var value_out4=paramsx[0].childNodes[7].innerHTML;
var value_out5=paramsx[0].childNodes[9].innerHTML;
var value_out6=paramsx[0].childNodes[11].innerHTML;
var value_out7=paramsx[0].childNodes[13].innerHTML;
var value_out8=paramsx[0].childNodes[15].innerHTML;
var value_out9=paramsx[0].childNodes[17].innerHTML;
var value_out10=paramsx[0].childNodes[19].innerHTML;
var value_out11=paramsx[0].childNodes[21].innerHTML;
var value_out12=paramsx[0].childNodes[23].innerHTML;
window.value_in1=value_in1;window.value_in2=value_in2;window.value_in3=value_in3;window.value_in4=value_in4;
window.value_in5=value_in5;window.value_in6=value_in6;window.value_in7=value_in7;window.value_in8=value_in8;
window.value_in9=value_in9;window.value_in10=value_in10;window.value_in11=value_in11;window.value_in12=value_in12;
window.value_out1=value_out1;window.value_out2=value_out2;window.value_out3=value_out3;window.value_out4=value_out4;
window.value_out5=value_out5;window.value_out6=value_out6;window.value_out7=value_out7;window.value_out8=value_out8;
window.value_out9=value_out9;window.value_out10=value_out10;window.value_out11=value_out11;window.value_out12=value_out12;
drawChart();
function drawChart(){
var data = google.visualization.arrayToDataTable([
['Mois', 'Frequence'],
[value_in1, parseInt(value_out1)],
[value_in2, parseInt(value_out2)],
[value_in3, parseInt(value_out3)],
[value_in4, parseInt(value_out4)],
[value_in5, parseInt(value_out5)],
[value_in6, parseInt(value_out6)],
[value_in7, parseInt(value_out7)],
[value_in8, parseInt(value_out8)],
[value_in9, parseInt(value_out9)],
[value_in10, parseInt(value_out10)],
[value_in11, parseInt(value_out11)],
[value_in12, parseInt(value_out12)],
]);
/*series: {
2 : { areaOpacity: 10 },
};
*/
var options = {
title: 'Fréquence des visites du site',
curveType: 'function',
legend: { position: 'bottom' },
backgroundColor: {
fill : 'transparent'
}
};
var chart = new google.visualization.AreaChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
} }
xml.send() ;
});
},30000);

Related

remove the ellipses in google barchart

I am using google Bar Chart and the text on the side is not showing fully. Is there a way to remove the ellipses?
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var byCollege = {!! $byCollege !!};
var info = [];
var Header = ['Element', 'الخريجين'];
info.push(Header);
for (const elem of byCollege) {
var temp = [];
temp.push(elem['college_name']);
temp.push(elem['total']);
info.push(temp);
}
drawBarChart(info, 'piechart_college');
}
function drawBarChart(info, charId) {
var view = new google.visualization.arrayToDataTable(info);
var chart = new google.visualization.BarChart(document.getElementById(charId));
chart.draw(view);
}
Thanks

Google Visualization Multiple Charts - Options Not Working

I have a multi-chart Google Visualization script (1 column chart and 2 line charts). The charts are working/displaying correctly except for the var Options code. The most important part of the Options section is being able to change the column/line color. So I tried changing it using the role: 'style'} alternative, but it didn't work either.
Please see below code for the 3 charts. I'm new to Google Visualization, so any feedback/help is much appreciated!
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
// Chart data
var data = [];
data[0] = google.visualization.arrayToDataTable ([["Date","Sessions", {role: 'style'}],
<?php
for($a = 0; $a < 7; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a].", 'fill-color: #76A7FA'],";
}
?>
]);
data[1] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < 31; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
data[2] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < count($query); $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
var current = 0;
var current_chart = 0;
// Create and draw the visualization
var chart = [];
chart[0] = new google.visualization.ColumnChart(document.getElementById('sessions_chart'));
chart[1] = new google.visualization.LineChart(document.getElementById('sessions_chart'));
function drawChart() {
// Disabling the buttons while the chart is drawing.
document.getElementById('week_btn').disabled = true;
document.getElementById('month_btn').disabled = true;
document.getElementById('all_btn').disabled = true;
google.visualization.events.addListener(chart, 'ready', function() {
// Enable the buttons after the chart has been drawn
document.getElementById('week_btn').disabled = false;
document.getElementById('month_btn').disabled = false;
document.getElementById('all_btn').disabled = false;
});
var view = new google.visualization.DataView(data[current]);
var options = {
title: 'Number of Sessions',
vAxis: {title: "# of Sessions", minValue:0},
hAxis: {format: 'MMM d, y'},
colors: 'lightgreen'
};
// Convert first column to date format
view.setColumns([{
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
},
label: data[current].getColumnLabel(0),
type: 'date'
}, 1]);
chart[current_chart].draw(view, data[current], options);
}
drawChart();
// google.charts.setOnLoadCallback(drawChart);
document.getElementById('week_btn').addEventListener("click", displayWeek);
function displayWeek() {
current = 0;
current_chart = 0;
drawChart();
}
document.getElementById('month_btn').addEventListener("click", displayMonth);
function displayMonth() {
current = 1;
current_chart = 1;
drawChart();
}
document.getElementById('all_btn').addEventListener("click", displayAll);
function displayAll() {
current = 2;
current_chart = 1;
drawChart();
}
});
the colors option should be an array...
colors: ['lightgreen']
as for the style role, try providing only the color...
echo "['".$date[$a]."', ".$sessions[$a].", '#76A7FA'],";
AND
highly recommend NOT building json manually in php from a string.
instead, separate the php from the html in two different files.
build the data in php and return the encoded json to the page.
then use ajax to call the php page and get the encoded json.
then draw the chart.
here are some examples...
How to automatically update Google Gauge
JSON $ajax problems

Using Thymeleaf with Google charts and Java Map

The Thymeleaf block I have made in JavaScript cuts off the ending ; of the variable, and throws an Uncaught (in promise) SyntaxError: Unexpected token ' in JSON at position 2.
The code does parse like it should, except for the data variable. Parsed code:
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = {'Expense1': 25.0, 'Expense2': 20.0, 'Expense3': 40.0};
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: 'Data test',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Pre Thymeleaf code:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = /*[[${chart.DataPoints}]]*/;
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: /*[[${chart.title}]]*/'',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
The data var is either like it is right now, or when enclosed in "", it cuts off the closing semi-colon. How do I get Thymeleaf of JavaScript to cast the data var to a string (while maintaining the '' it contains)?
Does this work for you? I don't think you need to build your data as a JSON string first, simply create it as a JavaScript object:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var json = {
'cols': [
{'id':'', 'label': 'Expense', 'pattern': '', 'type': 'string'},
{'id':'', 'label': 'Amount', 'pattern': '', 'type': 'number'}
],
rows: []
};
var data = /*[[${chart.DataPoints}]]*/ [];
var rows = [];
Object.keys(data).forEach(function(key) {
rows.push({
"c": [
{"v": key, "f": null},
{"v": data[key], "f": null}
]
});
});
json['rows'] = rows;
var data = new google.visualization.DataTable(json);
var title = /*[[${chart.title}]]*/ '';
var options = {
title: title,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
edit: you can format the data however you want... it's pretty trivial to do in JavaScript.

Unable to display actual chart using Google API in Javascript

I am displaying a chart using Google API and I am getting a chart but it is not displaying that line in the graph,
This is the code I am trying with, I am using array data for charts,
var jsonlength = data.feed.entry.length;
var timestamp = new Array(jsonlength);
var temperature = new Array(jsonlength);
var tempid = new Array(jsonlength);
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = ((data.feed.entry[i].gsx$temperaturevalue.$t));
}
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
console.log(i);
data1.addRows(i,data.feed.entry[i].gsx$temperaturevalue.$t);
//Here I can display all those values, But still not getting the chart, Though I have given proper values, Help me here
console.log(data.feed.entry[i].gsx$temperaturevalue.$t);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
This is the output I am getting without a line, Please help me I am new to this
Output without a line in the graph
most likely is due to 'string' values vs. number
try this...
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
here...
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
}
EDIT
here, you create data
var data = new google.visualization.DataTable();
but then you're adding columns to data1 ???
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
try syncing up the variable names and check addRow below...
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
// use addRow -- which takes an array
data1.addRow([i,data.feed.entry[i].gsx$temperaturevalue.$t]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);

how to receive a variable from $.get of function?

Help me please ...
I have two function and question - as to me to receive the chartData variable as AmCharts:
$.get(
"/ITN/TEST/chart_test_JSON_REQUEST/",
{
param1:'title',
param2:'BTSnum'
},
function(data) {
var s = JSON.stringify(data);
var chart;
var chartData = s
alert(chartData)
}
);
AmCharts.ready(function () {
var chartData ????????????????????????????????
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.write('chartdiv');
});
You should make use of JavaScript closures to get the data in the chartData variable using the callback function.
Note how in the callback the chartData variable is not preceded with a var statement. This means that the variable is not local and it references the same variable as the first chartData of the function.
AmCharts.ready(function () {
var chartData;
$.get(
"/ITN/TEST/chart_test_JSON_REQUEST/",
{
param1:'title',
param2:'BTSnum'
},
function(data) {
chartData = JSON.Parse(data);
}
);
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.write('chartdiv');
});
Excuse for the wrong formatting - when sending a question - already I understood and next time I will correctly format... (it is my first question)
AmCharts.ready(function () {
var chartData;
$.get(
"/ITN/TEST/chart_test_JSON_REQUEST/",
{
param1:'title',
param2:'BTSnum'
},
function(data) {
chartData = JSON.Parse(data);
}
);
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.write('chartdiv');
});
I have errors :
chartData is undefined
JSON.Parse is not a function

Categories