Google Visualization PHP and Javascript - javascript

I am creating a chart using a while loop to get the variables from a mysql query.
I am attempting to add html to the first column and it is causing the following issue: [object Object] does not fit either the Control or Visualization specification.
So, the table displays correctly but my category filters are now throwing this error. Can someone take a look at my code and see what i am missing? Thanks!
Here is my code:
echo "<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<body>
<br><br>
<div id='dashboard'>
<div style='float:left;' id='control1'></div>
<div style='float:left;' id='control2'></div>
<div style='float:left;' id='control4'></div>
<br><br>
<div style='float:left;' id='control3'></div>
<div style='float:left;' id='control5'></div>
<br><br>
<div id='table'></div>
</div>
</body>";
echo "<script>
google.load('visualization', '1.0', {packages:['corechart', 'table', 'controls']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Save');
data.addColumn('string', 'School');
data.addColumn('string', 'State');
data.addColumn('string', 'Scholarship Type');
data.addColumn('string', 'Scholarship Amount');
data.addColumn('string', 'For International');";
while ($schools = mysql_fetch_row($schoolsearch)) {
$schoolnames = str_replace(array('.', ',', "'"), '' , $schools[2]);
echo "data.addRows([
['<input type=\"checkbox\">', '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";
}
echo "var name_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'School',
}
});
var state_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'State',
}
});
var scholarshiptype_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control3',
'options': {
'filterColumnLabel': 'Scholarship Type',
}
});
var scholarshipamount_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control4',
'options': {
'filterColumnLabel': 'Scholarship Amount',
}
});
var international_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control5',
'options': {
'filterColumnLabel': 'For International',
}
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table',
});
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(data, {
allowHtml:true,
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
dashboard.bind([name_filter, state_filter, scholarshiptype_filter, scholarshipamount_filter, international_filter], [table]);
dashboard.draw(data);
}
</script>

I was able to fix this by placing the allowHtml in the options like this:
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table',
options: {
allowHtml: true
},
});

another option, which may work better, depending on if you want the filter to work on the html or the value it represents...
each cell in a DataTable has a value (v:) and a formatted value (f:)
you can use the formatted value for the html
where you have...
echo "data.addRows([
['<input type=\"checkbox\">', '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";
try...
echo "data.addRows([
[{v: '', f: '<input type=\"checkbox\">'}, '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";

Related

Google Line Chart - How to display data to linegraph

See the following data.DataTable
How do I input this data into Google Line Charts with filter for each Column AND filter for the Dates.
I would like my graph to have x-axis of dates and y-axis with the percentage. Also each row of data is its own line in the line graph. Is this possible?
Below is a snippet part of my code:
var data = google.visualization.arrayToDataTable(response,false);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard-div'));
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table-div',
'options': {'backgroundColor': 'lightgrey'}
});
var numCol = [3];
for (var i = 10; i < data.getNumberOfColumns(); i++) {
numCol.push(i);
}
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'linechart-div',
'view': {'columns': numCol},
'options': {'backgroundColor': 'lightgrey', 'title': 'InterCarrier Trunk Capacity Graph', 'explorer': {
'actions': ['dragToZoom', 'rightClickToReset'],
'axis': 'horizontal',
}}
});
var Slider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div1',
'options': {
'filterColumnLabel': '3/1/2020'
}
});
var Slider2 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div2',
'options': {
'filterColumnLabel': '3/2/2020'
}
});
var Slider3 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div3',
'options': {
'filterColumnLabel': '3/3/2020'
}
});
var Slider4 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div4',
'options': {
'filterColumnLabel': '3/4/2020'
}
});
Chart Here

Loop trough JSON with Ajax and pass value to Google Chart

I have the following Javascript code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
var jsonvalues = $.getJSON("http://localhost:5000/data", function(results) {
$.each(results, function(index) {
alert(results[index].key[1]);
});
});
$
var data = google.visualization.arrayToDataTable([
['Year','Targets', 'Total targets'],
{% for info in jsonvalues %}
['{{info['key'][1]|safe}}','{{info['key'][0]|safe}}', parseInt('{{info['value']|safe}}')],
{% endfor %}
]);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
What I am trying to achieve is to pass the getJSON data that I retrieve with the Ajax call from http://localhost:5000/data to the Google Chart.
I tried a lot of things but so far I am stuck and don't really know how to achieve what I want. I just inserted the alert aspect as test to see if this returns the data. The alert gives me back the JSON data that I am requesting, so that's fine.
MY JSON Data looks as follow:
[
{
key: [
"Abortion Related",
1977
],
value: 4
},
{
key: [
"Abortion Related",
1978
],
value: 6
}
]
Getting back to the question I had yesterday, solved it with the following working code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
function updateDiv() {
$(document).ready(function(){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Year');
data.addColumn('string', 'Targets');
data.addColumn('number', 'Total Targets');
values = new Array;
$.getJSON("http://localhost:5000/data", function(results)
{
$.each(results, function(index)
{
values.push([results[index].key[1],results[index].key[0],results[index].value]);
});
data.addRows(values);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
});
}); } setInterval(updateDiv, 5000)
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
First I changed from arrayToDatatable to DataTable. After that I declared the columns and
the type of data with data.addColumn. Then I moved the getJSONwithin the `var data. And that did the trick for me. More information can be found over here: https://developers.google.com/chart/interactive/docs/reference

Resizing google visualization with ChartEditor

is it possible to set the width and height of a chart when using the google visualization ChartEditor?
I require the chart to be 100% the width of the page and then set the height in pixels, currently when I set the width and height in the options they are being ignored.
the code that I have worked on so far is below:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
var chartEditor = null;
window.onresize = function() {
loadEditor();
};
function loadEditor() {
var data = google.visualization.arrayToDataTable([#Html.Raw(#ViewBag.ChartData)]);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
var rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'VAR1',
'ui': {
'label': 'Years'
}
}
});
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_div'));
}
</script>
the chart also incorporates a CategoryFilter linked with a dashboard is required to work with the chart displayed.
Currently when the chart is rendered it is fairly small.
Something like this should work, I switched out the data and modified the slider to get the snippet to work.
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
window.addEventListener('resize', redrawChart, false);
var chartEditor;
var data;
var dashboard;
var rangeSlider;
var wrapper;
function loadEditor() {
data = google.visualization.arrayToDataTable([
['Element', 'Density'],
['Copper', 8.94],
['Silver', 10.49],
['Gold', 19.30],
['Platinum', 21.45]
]);
dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Density',
'ui': {
'label': 'Density'
}
}
});
wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', drawChart);
chartEditor.openDialog(wrapper, {});
}
function drawChart() {
wrapper = chartEditor.getChartWrapper();
redrawChart();
}
function redrawChart() {
var height;
var width;
height = '200px';
width = Math.min(document.documentElement.clientWidth, window.innerWidth || 0) + 'px';
wrapper.setOption('height', height);
wrapper.setOption('width', width);
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
<script src="https://www.google.com/jsapi"></script>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>

Charts API error -- [one or more participants failed to draw()]

I am currently experiencing --> [one or more participants failed to draw()] error on the client side. I am able to get data to output in the drawVisualisation call, hence the issue is within the javascript code. I followed example but I cannot seem to figure out where I may be going wrong to trigger the error.
function drawVisualization(dataValues, chartTitle, columnNames, categoryCaption) {
if (dataValues.length < 1)
return;
var data = new google.visualization.DataTable();
data.addColumn('string', columnNames.split(',')[0]);
data.addColumn('string', columnNames.split(',')[1]);
data.addColumn('number', columnNames.split(',')[2]);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].Type, dataValues[i].PType, dataValues[i].COUNT]);
}
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'width': '1200',
'height': '500',
'legend': 'none'
},
'view': { 'columns': [2, 0] }
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': { 'height': '25em', 'width': '80em' }
});
var categoryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'Contorl1',
'options': {
'filterColumnLabel': columnNames.split(',')[1],
'filterColumnIndex': '1',
'ui': {
'label': 'Price'
}
}
});
new google.visualization.Dashboard(document.getElementById('PieChartExample')).bind([categoryPicker], [line, table]).draw(data);
}
</script>
<div id="PieChartExample">
<table>
<tr style='vertical-align: top'>
<td >
<div style="float: left;" id="chart1"></div>
</td>
</tr>
<tr>
<td >
<div style="float: left;" id="chart2"></div>
</td>
</tr>
<tr>
<td style='width: 600px'>
<div style="float: left;" id="control2"></div>
</td>
</tr>
</table>
</div>
Server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ClientScript.RegisterStartupScript(this.GetType(), "TestInitPageScript",
string.Format("<script type=\"text/javascript\">google.load('visualization','1.0',{{'packages':['corechart','controls']}});google.setOnLoadCallback(function(){{drawVisualization({0},'{1}','{2}');}});</script>",
jss.Serialize(GetData()),
"Name Example",
"Type,"));
}
}
[WebMethod]
public static List<Data3> GetData()
{
SqlConnection conn = new SqlConnection("##############");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "SELECT [Type], Cover, COUNT(Cover) AS 'Total' FROM [dbo].[database_qy] WHERE [Type] in ('bs','as') GROUP BY Cover, [Type] order by Cover";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data3> dataList = new List<Data3>();
string cov = "";
string typ = "";
int val = 0;
foreach (DataRow dr in dt.Rows)
{
try
{
cov = dr[0].ToString();
typ = dr[1].ToString();
val = Convert.ToInt32(dr[2]);
}
catch
{
}
dataList.Add(new Data3(cov, typ, val));
}
return dataList;
}
I am also getting returned to drawVisualisation call, as shown below;
<script type="text/javascript">google.load('visualization','1.0',{'packages': ['corechart','controls']});google.setOnLoadCallback(function(){drawVisualization([{"Type":"bs","PType":"cv","COUNT":2576},{"Type":"cd","PType":"cv","COUNT":2056},{"Type":"cl","PType":"cv","COUNT":9901},{"Type":"cm","PType":"cv","COUNT":10079},{"Type":"rm","PType":"cv","COUNT":12242},{"Type":"bs","PType":"tk","COUNT":3678},{"Type":"cd","PType":"tk","COUNT":7567},{"Type":"cl","PType":"tk","COUNT":42976},{"Type":"cm","PType":"tk","COUNT":21245},{"Type":"rm","PType":"tk","COUNT":44379},{"Type":"bs","PType":"TRD","COUNT":7},{"Type":"cd","PType":"TRD","COUNT":50},{"Type":"cl","PType":"TRD","COUNT":86},{"Type":"cm","PType":"TRD","COUNT":202},{"Type":"rm","PType":"TRD","COUNT":116}],'Name Example','Type,');});</script></form>
Please advice. Thanks
The problem is in the line ChartWrapper's view. The columns you specified ([2, 0]) do not work, as column 0 is a "string" type and cannot be a data series in the chart. Change it to [0, 2] and the dashboard will draw.
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'width': '1200',
'height': '500',
'legend': 'none'
},
'view': { 'columns': [0, 2] }
});
See working example: http://jsfiddle.net/asgallant/8D64L/

Google chart percentage slider

<script type="text/javascript">
function drawVisualization1(dataValues, chartTitle, columnNames, categoryCaption) {
if (dataValues.length < 1)
return;
var data = new google.visualization.DataTable();
data.addColumn('string', columnNames.split(',')[0]);
data.addColumn('string', columnNames.split(',')[1]);
data.addColumn('string', columnNames.split(',')[2]);
data.addColumn('string', columnNames.split(',')[3]);
data.addColumn('string', columnNames.split(',')[4]);
data.addColumn('string', columnNames.split(',')[5]);
data.addColumn('number', columnNames.split(',')[6]);
data.addColumn('number', columnNames.split(',')[7]);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].Value1, dataValues[i].Value2, dataValues[i].Value3, dataValues[i].Value4, dataValues[i].Value5, dataValues[i].Value6,( dataValues[i].Value7)/100, (dataValues[i].Value8)/100]);
}
var formatter = new google.visualization.NumberFormat({ pattern: '####%' });
formatter.format(data, 6);
var formatter = new google.visualization.NumberFormat({ pattern: '####%' });
formatter.format(data, 7);
var categoryPicker1 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'Container',
'options': {
'filterColumnLabel': columnNames.split(',')[2],
'ui': {
'labelStacking': 'horizontal',
'allowTyping': false,
'allowMultiple': false,
'caption': categoryCaption,
'label': columnNames.split(',')[2]
}
}
});
var slider1 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'Slider',
'options': {
'filterColumnLabel': columnNames.split(',')[6],
'ui': { 'labelStacking': 'horizontal' },
'ui.format': { 'pattern':'####%' }
}
});
var table1 = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'TableContainer1',
'options': {
'width': '895px',
'page': 'enable',
'pageSize': 5
}
});
new google.visualization.Dashboard(document.getElementById('PieChartExample')).bind([categoryPicker1, slider1], [table1]).draw(data);
}
</script>
Script code to generate google chart my problem is i am not able to show the slider for percentage values;i am converting that table values into percentage and i want to show in the slider value.can anyone help me to resolve.
var slider1 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'Slider',
'options': {
'filterColumnLabel': columnNames.split(',')[6],
'ui': { 'labelStacking': 'horizontal',
'format': { 'pattern':'####%' } }
}
});

Categories

Resources