Reloading and then refreshing in same function jquery - javascript

In my PHP application I'm using 2 php files.
chart.php - Page contains a google chart.
<div id="chart_div" style="height:100%;width:100%">
</div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage'],
["King's pawn (e4)", 44],
["Queen's pawn (d4)", 31],
["Knight to King 3 (Nf3)", 12],
["Queen's bishop pawn (c4)", 10],
['Other', 3]
]);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
};
function selectHandler() {
window.location.href = "chart.php";
}
</script>
2. index.php - Home page where I'm including chart.php in a div
<div style="width:40%">
require_once 'chart.php';
</div>
On clicking the chart in index.php page , it will call selectHandler() and redirect to chart.php.
The issue is, the chart in chart.php (after redirecting from index.php) is showing in small size similar to the chart display in index.php. Once I refreshes the chart.php it will display the chart in correct size.
Is there any function in jquery to refresh a page by reloading other than using location.reload().
Can anyone help me to fix this issue? Thanks in advance.

try redrawing the chart,
use an inline function on your select handler,
so you can still access your chart, data, and options.
google.visualization.events.addListener(chart, 'select', function () {
window.location.href = "chart.php";
chart.draw(data, options);
});

Related

Why doesn't my Google chart work on Safari?

I am trying to draw a chart on screen using Google charts. It works on every browser except for Safari. The following is the code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the bar chart package.
google.charts.load("current", {"packages":["corechart", "line"]});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "/get-data-for-chart",
data: {"objectId": 807},
dataType: "json"
}).then(function(response) {
// Create our data table out of JSON data loaded from server.
rawData = response;
if (rawData.rows != null) rawData.rows = rawData.rows.map(row => ({ c: [{ v: new Date(row.c[0].v) }, row.c[1]] }));
var data = new google.visualization.DataTable(rawData);
// Instantiate and draw our chart, passing in some options.
var options = {
chart: {
title: "Title of the chart"
},
width: 900,
height: 500,
hAxis: {
title: "Time Axis",
format: "MM-dd",
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: "none"},
minValue: 0,
format: "currency"
}
};
var date_formatter = new google.visualization.DateFormat({
pattern: "MMM dd, yyyy HH:mm"
});
date_formatter.format(data, 0);
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, options);
});
}
</script>
<!--Div that will hold the chart-->
<div id="chart_div"></div>
What actually happens on Safari is that the area for the chart loads, but with incorrect labels I guess. And the actual chart does not load at all. Moreover, there are no errors shown in the console, so I can't debug this in a usual way. As mentioned earlier, this works with all other browsers. Also for the record, the Safari is running on MacOS Mojave. Any help is greatly appreciated! Thanks.

Animating single line chart using javascript

I am new to Google Line Chart. The chart which I try to draw is drawn properly but I want to animate it. I tried using animation section in code but seems it does not work at all on single line chart.
google.charts.load('current', {
'packages': ['line']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Test');
data.addColumn('number', 'Test 2');
data.addRows([
[1, 37.8],
[2, 30.9],
[3, 25.4],
[4, 11.7]
]);
var options = {
animation: {
duration: 1000,
startup: true, //This is the new option
easing: 'out',
},
aggregationTarget: 'category',
chart: {
title: 'Test 1',
subtitle: 'Test 2'
},
width: '98%',
height: 300,
axes: {
x: {
0: {
side: 'top'
}
}
}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_top_x"></div>
animation isn't supported on Material charts
in fact, there are several options Material charts do not support
see --> Tracking Issue for Material Chart Feature Parity #2143
Material charts --> google.charts.Line -- packages: ['line']
Core charts --> google.visualization.LineChart -- packages: ['corechart']
using a Core chart with the following option will display similar to Material
theme: 'material'

Google Bar chart Bar color not changing

I'm using google bar chart to represent set of issues into different categories like open, closed, in progress etc., I'm getting the count of different categories and storing it to a hashmap, and then I retrieve the data from hashmap and displaying it in the bar chart using the below code.
Edited below is the code that I'm using. I've included it in a jsp page
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawBarChart);
function drawBarChart() {
var data = google.visualization.arrayToDataTable([
['Status', 'No. of Issues', { role: 'style' }],
<%for(String SC:StatusCount.keySet()){
%>
['<%=SC.toString()%>',<%=StatusCount.get(SC.toString())%>, 'blue'],
<%
}
%>
<%for(String EC:EscCount.keySet()){
%>
['<%=EC.toString()%>',<%=EscCount.get(EC.toString())%>, 'red' ],
<%
}
%>
]);
var options = {
chart: {
title: 'Performance',
},
is3D: true,
titleTextStyle: {
fontName: 'Arial',
fontSize: 20
},
'width':550,
'height':400,
backgroundColor: 'transparent',
bars: 'vertical' // Required for Material Bar Charts.
};
var barchart = new google.charts.Bar(document.getElementById('barchart_material'));
barchart.draw(data, google.charts.Bar.convertOptions(options));
}
StatusCount is used for the status count and EscCount for the no of escalations. I wanted to change the color of the Escalations bar. But when I specify the color, it's not getting changed. Used the same thing that Google itself has given to change the color.
Kindly help. Thanks in advance
Column Roles, including 'style' are only supported by Classic charts...
Classic --> google.visualization.BarChart & ColumnChart --> packages: ['corechart']
Material --> google.charts.Bar --> packages: ['bar']
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Status', 'No. of Issues', { role: 'style' }],
['Closed',14, 'blue'],
['On Hold',8, 'blue'],
['In Progress',20, 'blue'],
['Open',24, 'blue'],
['Escalations',4, 'red'],
]);
var chart = new google.visualization.BarChart(
document.getElementById('chart_div')
);
chart.draw(data, {
theme: 'material'
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Multiple Google Charts

I am attempting to create multiple Google Charts, but I can't get it to work. I've tried everything I could find on Stack Overflow. I most recently attempted this fix, but it didn't work. I think I may be missing something. Can anyone see anything wrong with the code as it stands now?
Expected Behavior:
Page displays bar graph. Then, a line graph is displayed underneath the bar graph.
Current Behavior:
Page displays bar graph. Line graph does not display.
Here is JSFiddle. On a side note, the JavaScript only seems to work inline on JSFiddle. If I moved it into the JavaScript section, it did not function properly. Maybe this has something to do with the external resource that was called?
Regardless, I am currently doing this all inline for this experiment.
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/jsapi" type="text/javascript">
</script>
<script type="text/javascript">
// Load the Visualization API and the chart packages.
google.load('visualization', '1.1', {
packages: ['line', 'bar', 'corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the charts, passes in the data and
// draws them.
function drawChart() {
// Create the data table.
var BarData = new google.visualization.arrayToDataTable([
['', 'Customer', 'Segment Avg'],
['TTM Sales', 4, 2],
['TTM Orders', 5, 3],
['TTM Categories', 7, 4]
]);
// Create the data table.
var LineData = new google.visualization.arrayToDataTable([
['Year', 'Customer', 'Segment Avg'],
['2011', 4, 5],
['2012', 5, 3],
['2013', 4, 2]
]);
// Set chart options
var BarOptions = {
chart: {
title: 'Performance',
},
width: 900,
height: 500
};
// Set chart options
var LineOptions = {
chart: {
title: 'Sales History'
},
width: 900,
height: 500
};
// Instantiate and draw our chart, passing in some options.
var BarChart = new google.charts.Bar(document.getElementById(
'bar_chart'));
BarChart.draw(BarData, BarOptions);
var LineChart = new google.charts.Line(document.getElementById(
'line_chart'));
LineChart.draw(LineData, LineOptions);
};
</script>
<title>Test Chart Page</title>
</head>
<body>
<!--Divs that will hold the charts-->
<div id="bar_chart"></div>
<div id="line_chart"></div>
</body>
</html>
It seems some changes have been made in the latest version of Google Charts API that causes this behavior, but there is a reliable way to render multiple charts on a single page. The idea is to render the next chart once the previous one is rendered, for that purpose you could utilize ready event handler.
Having said that, replace
var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
barChart.draw(barData, barOptions);
var lineChart = new google.charts.Line(document.getElementById('line_chart'));
lineChart.draw(lineData, lineOptions);
with
var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
google.visualization.events.addOneTimeListener(barChart, 'ready', function () {
var lineChart = new google.charts.Line(document.getElementById('line_chart'));
lineChart.draw(lineData, lineOptions);
});
barChart.draw(barData, barOptions);
Working example
google.load('visualization', '1.1', {
packages: ['line', 'bar', 'corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
function drawCharts() {
// Create the data table.
var barData = new google.visualization.arrayToDataTable([
['', 'Customer', 'Segment Avg'],
['TTM Sales', 4, 2],
['TTM Orders', 5, 3],
['TTM Categories', 7, 4]
]);
// Create the data table.
var lineData = new google.visualization.arrayToDataTable([
['Year', 'Customer', 'Segment Avg'],
['2011', 4, 5],
['2012', 5, 3],
['2013', 4, 2]
]);
// Set chart options
var barOptions = {
chart: {
title: 'Performance',
},
width: 900,
height: 500
};
// Set chart options
var lineOptions = {
chart: {
title: 'Sales History'
},
width: 900,
height: 500
};
var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
google.visualization.events.addOneTimeListener(barChart, 'ready', function () {
var lineChart = new google.charts.Line(document.getElementById('line_chart'));
lineChart.draw(lineData, lineOptions);
});
barChart.draw(barData, barOptions);
};
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<div id="bar_chart"></div>
<div id="line_chart"></div>
Works with setTimeout:
// Instantiate and draw our chart, passing in some options.
var BarChart = new google.charts.Bar(document.getElementById(
'bar_chart'));
setTimeout(function() {
BarChart.draw(BarData, BarOptions);
}, 0);
var LineChart = new google.charts.Line(document.getElementById(
'line_chart'));
setTimeout(function() {
LineChart.draw(LineData, LineOptions);
}, 1e3);
Updated JSFiddle
The code below works by creating the second chart inside of setTimeout.
I don't know what is causing the problem,
but at least you have a workaround.
fiddle
<script type="text/javascript">
// Load the Visualization API and the chart packages.
google.load('visualization', '1.1', {
packages: ['line', 'bar', 'corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the charts, passes in the data and
// draws them.
function drawChart() {
// Create the data table.
var BarData = new google.visualization.arrayToDataTable([
['', 'Customer', 'Segment Avg'],
['TTM Sales', 4, 2],
['TTM Orders', 5, 3],
['TTM Categories', 7, 4]
]);
// Create the data table.
var LineData = new google.visualization.arrayToDataTable([
['Year', 'Customer', 'Segment Avg'],
['2011', 4, 5],
['2012', 5, 3],
['2013', 4, 2]
]);
// Set chart options
var BarOptions = {
chart: {
title: 'Performance',
},
width: 900,
height: 500
};
// Set chart options
var LineOptions = {
chart: {
title: 'Sales History'
},
width: 900,
height: 500
};
// Instantiate and draw our chart, passing in some options.
var BarChart = new google.charts.Bar(document.getElementById(
'bar_chart'));
var LineChart = new google.charts.Line(document.getElementById(
'line_chart'));
LineChart.draw(LineData, LineOptions);
setTimeout(function(){
BarChart.draw(BarData, BarOptions);
},50);
};
</script>
<body>
<!--Divs that will hold the charts-->
<div id="bar_chart"></div>
<div id="line_chart"></div>
</body>
Google fixed this timing issue in a recent release, available with the frozen version loader: https://developers.google.com/chart/interactive/docs/library_loading_enhancements#frozen-versions
Relevant thread: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/google-visualization-api/KulpuT418cg/yZieM8buCQAJ

Change the color of some bars in google chart

I created an horizontal bar chart with Google Charts and I want to change the color of the bars that belongs to a certain range, I tried to do it by many ways
but in vain, here is my code :
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Agents', 'Percentage' ],
<?php
for($i=0;$i<sizeof($name);$i++){
echo '[\''.$name[$i].'\','.$count[$i].'],';
}
?>
]);
var options = {
title: 'EKMS Usage per agent',
width: 900,
legend: { position: 'none' },
chart: { title: 'EKMS Usage per agent',
subtitle: 'By percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
$name and $count are two arrays that I retrieved from my database and that has the same length, I tried to add a column { role: "style" } in the variable data and to
assign colors using a test like this :
var data = new google.visualization.arrayToDataTable([
['Agents', 'Percentage', { role: "style" } ],
<?php
for($i=0;$i<sizeof($name);$i++){
if($count[$i]<50)
echo '[\''.$name[$i].'\','.$count[$i].',\'red\'],';
else
echo '[\''.$name[$i].'\','.$count[$i].',\'blue\'],';
}
?>
]);
I tried also to add colors : ['blue','red'] and it changes the color of all the bars.
P.S : Note that the chart that I used is : Top X Chart Here is its link :
https://google-developers.appspot.com/chart/interactive/docs/gallery/barchart#top-x-charts
It seems that google.charts.Bar component does not support style role, but you could utilize google.visualization.BarChart component from corechart package instead to customize bar styles as demonstrated below.
Example
//google.load("visualization", "1.1", {packages:["bar"]});
google.load("visualization", "1.1", {packages:["corechart"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage', { role: "style" }],
["King's pawn (e4)", 44, "#b87333"],
["Queen's pawn (d4)", 31, "silver"],
["Knight to King 3 (Nf3)", 12, "gold"],
["Queen's bishop pawn (c4)", 10, "color: #e5e4e2"],
['Other', 3,"green"]
]);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('top_x_div'));
var chart = new google.visualization.BarChart(document.getElementById("top_x_div"));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div" style="width: 900px; height: 500px;"></div>

Categories