I am creating a report in a health application using google charts. Due to the way that the application works, I have to define the data for the chart in an XSL document and then use javascript to grab and use that data. I can't run the javascript inline within the XSL - the application blocks it.
The XSL works fine and gives me the following :-
<div id="mydata" style="display:none;">
[{c:[{v: new Date(2020,3,21)}, {v:94.05}]},
{c:[{v: new Date(2020,3,29)}, {v:94.3}]},
{c:[{v: new Date(2020,4,5)}, {v:95}]},]
</div>
My javascript then looks like this:-
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var mydata=$("#mydata").text()
var mydata=mydata.replace("},]", "}]");
var myconfig="{cols: [{id: 'Date', label: 'Date', type: 'date'},{id: 'Weight', label: 'Weight', type:'number'}],rows: " + mydata + "}"
function drawChart() {
var data = new google.visualization.DataTable(myconfig);
var options = {
title: 'Patient Weight',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
The problem is that it doesn't work. I get :
Uncaught (in promise) SyntaxError: Unexpected token c in JSON at position 0
at JSON.parse (<anonymous>)
at gvjs_Li (jsapi_compiled_default_module.js:55)
at new gvjs_L (jsapi_compiled_default_module.js:161)
at drawChart (<anonymous>:8:20)
If I copy the value out of myconfig and paste it into the google visualisation it works perfectly. This is the resultant myconfig variable:-
cols: [{id: 'Date', label: 'Date', type: 'date'},{id: 'Weight', label: 'Weight', type:'number'}],rows:
[{c:[{v: new Date(2020,3,21)}, {v:94.05}]},{c:[{v: new Date(2020,3,29)}, {v:94.3}]},{c:[{v: new Date(2020,4,5)}, {v:95}]}]}
This is driving me mad .Please help!
UPDATE:
Finally cracked this!!
I put the cols definition into the DIV as well and put quotes around EVERYTHING, removed the "new" as suggested and finally it works!!