Google Charts displays only after clicking on inspect element - javascript

I am using Google Charts to display a pie chart on my webpage. I display the charts by pulling data from my database, using JavaScript and PHP.
However, I encountered a problem whereby my chart only displays when I right-click to inspect element. I'm not sure if there's anything wrong with my codes.
Here's the code for JavaScript:
google.charts.load("current", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData =
$.ajax({
type: "POST",
url: "./handle/getChartsInfo.php",
dataType: 'json',
async: false
}).responseText;
var chartData = new google.visualization.DataTable(jsonData);
var options = {
title: 'My Policies',
pieHole: 0.5,
pieSliceText: 'none',
tooltip: {isHtml: true},
backgroundColor: 'none',
colors: ["#F7464A", "#46BFBD", "#FDB45C"]
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(chartData, options);
}
I am also getting a warning on Chrome whereby it says:
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
Thank you in advance for any help!

removing async: false will prevent the Synchronous XMLHttpRequest warning
google.charts.load('current', {
callback: function () {
$.ajax({
type: 'POST',
url: './handle/getChartsInfo.php',
dataType: 'json'
}).done(function (jsonData) {
var chartData = new google.visualization.DataTable(jsonData);
var options = {
title: 'My Policies',
pieHole: 0.5,
pieSliceText: 'none',
tooltip: {isHtml: true},
backgroundColor: 'none',
colors: ['#F7464A', '#46BFBD', '#FDB45C']
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(chartData, options);
}).fail(function (jq, text, errMsg) {
console.log(errMsg);
});
},
packages:['corechart']
});

Related

How to load charts in background using JavaScript?

I've been using few type of google's charts (l load the Google Charts with Ajax) in my apps.
Before I can do anything in my application I have to wait until all the charts have been loaded. So it takes time. I would like to load charts in the background so that I can continue using the application.
I've already tried setTimeout, promise function but it didn't work.
I am asking for any advice.
Thank you :)
This is one of my charts:
DesktopManager.loadMonthChart = function () {
$.ajax({
url: Routing.generate('...'),
success: function (data) {
DesktopManager.showContentAndHideLoader('window-month-chart');
var dataForChart = [];
for (var value in data.values) {
dataForChart.push([value, data.values[value]]);
}
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(dataForChart);
var options = {
title: '',
animation: {
startup: true,
duration: 5000,
easing: 'out',
},
curveType: 'function',
legend: {position: 'none'},
hAxis: {textPosition: 'none'},
backgroundColor: '#f7f7f7',
colors: ['#7cab30']
};
var chart = new google.visualization.LineChart(document.getElementById('desktop-item-chart'));
chart.draw(data, options);
}
},
error: function (data) {
DesktopManager.showErrorMessage('window-month-chart');
}
});
}

google column chart change bar color not set dynamically

i want to set different column color . Only one color show in column . How i set dynamic color in google column color.
How can i set dynamic color of every column color .
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Dashboard/mTotalFileRefWise",
data: JSON.stringify({ PhaseID: $("#Projectlist").val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
var options = {
title: '',
legend: { position: 'none', maxLines: 9 },
colors: ['#00c0ef', '#DD4B39', '#DD4B39'],
width:500,
height:340,
animation: {
duration: 2000,
easing: 'out',
startup: true,
}
};
var chart = new google.visualization.ColumnChart($("#TotalFilesRefwise")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
$("#Projectlist").change(function () {
drawChart();
});
</script>
the colors configuration option applies each color in the array to each series in the data table
series are defined by y-axis columns in the data table,
which is each column after the x-axis, the first column
since you only have one y-axis column, only one color is applied
another method to apply colors is using a style column role in the data table
this allows you to define the color for each bar, right in the data table,
for example...
[
["Category","TotalAmount",{type:'string',role:'style'}], // <-- style role
["COST OF LAND",1572.2,'#00c0ef'], // <-- bar color
["DEVELOPMENT CHARGES",54.1,'#DD4B39']
]
if you don't want to change how the data is being built,
you can use a data view to assign the colors...
here, a data view is created, and a calculated column is added to determine the color.
the colors are pulled from the colors config option, based on row index of the data table...
(just be sure there are the same number of colors as there are rows in the data table)
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
role: 'style',
type: 'string',
calc: function (dt, row) {
return options.colors[row]
}
}]);
see following working snippet...
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var r = [["Category","TotalAmount"],["COST OF LAND",1572.2],["DEVELOPMENT CHARGES",54.1]];
var data = google.visualization.arrayToDataTable(r);
var options = {
title: '',
legend: { position: 'none', maxLines: 9 },
colors: ['#00c0ef', '#DD4B39', '#DD4B39'],
width:500,
height:340,
animation: {
duration: 2000,
easing: 'out',
startup: true,
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
role: 'style',
type: 'string',
calc: function (dt, row) {
return options.colors[row]
}
}]);
var chart = new google.visualization.ColumnChart($("#TotalFilesRefwise")[0]);
chart.draw(view, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="TotalFilesRefwise"></div>
note: need to use the correct version of google charts,
the jsapi library should no longer be used...
the new library...
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load and setOnLoadCallback statements,
see snippet above...

Google Pie Chart Is Not Responsive

I am trying to make my chart responsive. I have added this code (as below) to make my chart responsive. But still it is not working. Can somebody help me to figure it out ? Thank you.
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "<?php echo base_url() . 'index.php/main/lihat_graph' ?>",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: '',
hAxis: {title: 'Jumlah Kepakaran'},
vAxis: {title: 'Jumlah Kepakaran'},
bubble: {textStyle: { fontName: 'arial', fontSize: 12 }},
colors: ['beige','pink','#00ADF9', 'maroon', 'red', 'green', 'purple', 'gray', 'orange']
};
if(data.getNumberOfRows() == 0){
$("#chart_div").append("Graf Bidang Kepakaran masih dalam proses
pengumpulan data. Graf akan dipaparkan setelah proses pengumpulan data
selesai.")
}else{
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(window).resize(function(){
drawChart();
});
</script>
Graph is the image of my graph.
your width is always 800. justify it to window size and do the math to make it nest in your box as you want.
width : window.innerWidth,
see this link and write a better code. the way you wrote has performance issue.
JQuery: How to call RESIZE event only once it's FINISHED resizing?

howto use vaxis in google charts materialview

I have been fiddling with a particle photon, posting data to sparkfun.com
To display this data I am trying to use google.visualization. But I cant seem to get the axis behaving as I want it to.
see (but wait a while it is slow): https://www.hanscees.com/photon/charts-data-sparkfunA.html
I want the caxis to show not 1K, but 1010 and so on. here is my code:
function drawChart1() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1},
data: {'lte' : {'timestamp' : 'now - 4 hours'}},
dataType: 'jsonp',
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Pressure');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.hectopascals)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: { title: 'Barometer Pressure'},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'Pressure'}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {label: 'Pressure (Hpa)'}
}
},
vAxis: {format: 'decimal'},
hAxis: {color: '#333', count: 8}
};
var materialChart = new google.charts.Line(ChartDivBaro);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
unfortunately, most vAxis options simply do not work on material charts...
see --> Tracking Issue for Material Chart Feature Parity #2143
recommend using a core chart instead...
you can use the following option to get the look and feel close to material
theme: 'material'
solved it without material:
var options = {title:'Pressure Outside',
width:550,
height:300,
vAxis: {format: '0'}
};
var chart = new google.visualization.LineChart($('#chart1').get(0));
chart.draw(data, options); // draw data
}); // results

Uncaught Error: Not an array

Im trying to populate a google chart with data that I'm fetching from an API at www.scb.se (The Swedish Statistics Bureau).
I'm using the following code:
$.ajax({
type: "POST",
url: 'http://api.scb.se/OV0104/v1/doris/sv/ssd/START/HA/HA0103/Livs',
data: '{"query":[{"code": "Varugrupp","selection":{"filter": "vs:VaruTjänstegrCoicopD","values":["01.1.7"]}},{"code": "ContentsCode","selection": {"filter": "item","values":["HA0103A1"]}},{"code": "Tid","selection":{"filter": "item","values": ["2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"]}}],"response": {"format": "json"}}',
success: function(data){
console.log(data);
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var jsonData = data;
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chartData = google.visualization.arrayToDataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(chartData, options);
}
}
});
When I "console.log(data)" I can see all the contents in the console but Charts keep telling me that data is not an array. What am I doing wrong?
Cheers!
The console log of "data":
Object {columns: Array[3], comments: Array[1], data: Array[11]}

Categories

Resources