How to load charts in background using JavaScript? - 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');
}
});
}

Related

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...

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

Google Charts displays only after clicking on inspect element

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']
});

Why does a spurios alert() cause Google Chart to draw correctly?

I'm trying to draw two Google Charts on the same webpage.
The code for the 2nd chart looks like this
function chart2() {
/* second chart (scatter plot) */
var data2 = new google.visualization.DataTable();
data2.addColumn('number', 'Date');
data2.addColumn('number', 'Sold Price');
var map = /*[[${worthTemplateData.pricingInfo['marketHistory']}]]*/ [];
map.forEach(function (item) {
data2.addRows([ [item.date, item.origPrice] ]);
});
alert('Please wait');
var options = {
width: 900,
height: 500,
chart: {
title: 'Price History',
subtitle: 'For similar-size units'
},
hAxis: {title: 'Date'},
vAxis: {title: 'Sold Price'}
};
var chart2 = new google.charts.Scatter(document.getElementById('google-chart2'));
chart2.draw(data2, google.charts.Scatter.convertOptions(options));
}
It works.
But as soon as I remove the alert('Please wait'); line, it doesn't work anymore! The screen area where the chart should be is empty.
I suspect there is some timing issue, even though JS is presumably "single-threaded".
What's more puzzling, if I change the order, only the other chart loads:
google.load("visualization", "1.0", {packages: ["bar", "scatter"]});
google.setOnLoadCallback(drawCharts);
function drawCharts() {
chart2();
chart1();
}
What's the fix?
There is an issue with drawing multiple material charts.
You could switch to Classic Scatter Charts: google.charts.Scatter -> google.visualization.ScatterChart or try with some delay:
function doSetTimeOutDrawChart(chart, data, options, delay){
setTimeout(function () {
chart.draw(data, options);
}, delay);
}
like in this example:
jsFiddle

Ajax dynamic data with column bar chart

Is it possible to run the highcharts column bar charts? I've tried it a couple of times and unfortunately this no real way to refresh the data without reloading it.
I whipped up some pseudo code which is the way I did it at work (I'm not there now so can't get to the code).
Should I whip up a loop and run it like 5,000 times or something with a 5 second delay? I'm not real sure how to proceed.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
< your typical ajax call function here
return some value;
>
$(function () {
<var ajax_far = ajax_function();>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Some Bar'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [ajax_var]
}]
});
});
}, 5000);
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
put your ajax code in one function that it call from ready function...try this
$(document).ready(function(){
example();
setInterval("example()",5000);
}
function example()
{
//ajax code here
}
The ajax call should simply obtain new data for the chart to display. There is no need to redraw the entire chart, you can just replace the series data, or add indivual points. Here is a good article on doing this on the highcharts website here http://docs.highcharts.com/#preprocessing-live-data, but the ajax code they suggest is:
/**
* Request data from the server, add it to the graph and set a timeout to request again.
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // Shift if the series is longer than 2.
// Add the point.
chart.series[0].addPoint(point, true, shift);
// Call it again after one second.
setTimeout(requestData, 1000);
},
cache: false
});
}
In this code, the requestData function is called every second (via setTimout). It obtains a new data point via an ajax call to live-server-data.php and uses chart.series[0].addPoint to add it to the chart.
If the ajax call returned the entire series, you would call chart.series[0].setData to replace the entiire series.
The only thing you need to worry about is making sure the chart is created before you start call addPoint or setData.
$(function () {
var chart;
var list;
$(document).ready(function() {
var options = {
chart: {
//all chart attr here
}
//other attr
}
chart = new Highcharts.Chart(options);
setInterval(function() {
$.ajax({
type: "GET",
url: "service",
dataType: "json",
success: function (data)
{
chart.series[0].setData(data);
}
}),1000); //will set ur data to ajax data every 1 sec
if u want to update to existing chart data try addPoint()
});
});

Categories

Resources