Google Visualization API load 2 scripts on the same HTML - javascript

Hello Im trying to load 2 scripts at the same page but they seem to be overlapping eachother.In the first script im getting a table with a few columns and cells. In the 2nd one im getting just a single cell from the second sheet tab but as i said they overlap eachother and i can see only one at a time. This is my first time using google visualizations and i tried to rename the variables and names but i get the same thing.Is there a way to merge both scripts in one and have the html page load both of them without overlapping. Thank you.
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
</head>
<body >
<div id="box">
<script src="js/google-sheets-html.js" type="text/javascript"></script>
<div id="table">
</div>
</div>
<div id="box2">
<script src="js/google-sheets-html2.js" type="text/javascript"></script>
<div id="table2">
</div>
</div>
</body>
</html>
First Script
google.load('visualization', '1', {
packages: ['table']
});
var visualization;
function drawVisualization() {
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=xxx&output=html&usp=sharing');
query.setQuery('SELECT A, B, C, D, E, F, G ,H ,I ORDER BY A DESC Limit 10 label A "Date", B "Agent", C "Client", D "Country", E "Desk", F "Department", G "Method", H "Amount", I "Currency"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
google.setOnLoadCallback(drawVisualization);
Second Script
google.load('visualization', '1', {
packages: ['table']
});
var visualization;
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?gid=xxx');
query.setQuery('SELECT A');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table2'));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
google.setOnLoadCallback(drawVisualization);

combine them into one script.
you only need to load google charts once,
regardless the number of tables / charts being drawn.
see following snippets...
HTML
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
</head>
<body >
<div id="box">
<div id="table">
</div>
</div>
<div id="box2">
<div id="table2">
</div>
</div>
<script src="js/google-sheets-html.js"></script>
</body>
</html>
JS
google.charts.load('current', {
packages: ['table']
}).then(function () {
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=xxx&output=html&usp=sharing');
query.setQuery('SELECT A, B, C, D, E, F, G ,H ,I ORDER BY A DESC Limit 10 label A "Date", B "Agent", C "Client", D "Country", E "Desk", F "Department", G "Method", H "Amount", I "Currency"');
query.send(function (response) {
handleQueryResponse(response, 'table');
});
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?gid=xxx');
query.setQuery('SELECT A');
query.send(function (response) {
handleQueryResponse(response, 'table2');
});
function handleQueryResponse(response, id) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById(id));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
});

Related

How to display column headers in Y axis for a Datatable using HighCharts?

I am using Datatables and HighCharts. Please see my code below. I am not sure how to display this bar chart where Years are displayed in Y axis. I have added an image below to show how it looks like.
I am new to HighCharts, so I am not sure of all the functions. Thanks.
How can I get graph to show like this? I want years in Y axis. Thanks.
http://live.datatables.net/febayaxa/1/edit
$(document).ready(function() {
var table = $("#example1").DataTable();
var salary = getSalaries(table);
// Declare axis for the column graph
var axis = {
id: "salary",
min: 0,
title: {
text: "Number"
}
};
// Declare inital series with the values from the getSalaries function
var series = {
name: "Overall",
data: Object.values(salary)
};
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series]
});
// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});
function getSalaries(table) {
var salaryCounts = {};
var salary = {};
// Get the row indexes for the rows displayed under the current search
var indexes = table
.rows({ search: "applied" })
.indexes()
.toArray();
// For each row, extract the office and add the salary to the array
for (var i = 0; i < indexes.length; i++) {
var office = table.cell(indexes[i], 0).data();
if (salaryCounts[office] === undefined) {
salaryCounts[office] = [+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, "")];
}
else {
salaryCounts[office].push(+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, ""));
}
}
// Extract the office names that are present in the table
var keys = Object.keys(salaryCounts);
// For each office work out the average salary
for (var i = 0; i < keys.length; i++) {
var length = salaryCounts[keys[i]].length;
var total = salaryCounts[keys[i]].reduce((a, b) => a + b, 0);
salary[keys[i]] = total / length;
}
return salary;
};
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example1" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr></tbody>
</tbody></table>
I am going to assume you mean the x-axis (the horizontal axis) when you say that you want to use the years (from the table headings) from your DataTable for each bar's label in the chart.
You can access these table headings using the DataTables API and some jQuery.
Use this to get an array of table heading elements:
api.columns().header()
And then use $(element).html() to get the label (the year) from each heading.
There is a lot of code in your example in the question which does not appear to be relevant to the chart you want to create, so in the following example, I removed all of that. If it is needed, you can put it back.
$(document).ready(function() {
var tableData = [];
var tableCategories = []
var table = $("#example1").DataTable({
initComplete: function(settings, json) {
let api = new $.fn.dataTable.Api(settings);
// get the seris data as an array of numbers from the table row data:
api.rows().data().toArray()[0].forEach(function(element, index) {
if (index > 0) {
tableData.push(parseFloat(element.replace(/,/g, '')));
}
});
// get the x-axis caregories from the table headings:
api.columns().header().toArray().forEach(function(element, index) {
if (index > 0) {
tableCategories.push($(element).html());
}
});
  
}
});
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: tableCategories
},
series: [{
data: tableData
}]
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example1" class="display nowrap" width="100%">
<thead>
<tr>
<th>Year</th>
<th>2012</th>
<th>2013</th>
<th>2014</th>
<th>2015</th>
<th>2016</th>
<th>2017</th>
<th>2018</th>
<th>2019</th>
<th>2020</th>
<th>2021</th>
</tr>
</thead>
<tr>
<td> Data</td>
<td>3,823</td>
<td>3,823</td>
<td>3,954</td>
<td>3,959</td>
<td>3,955</td>
<td>3,956</td>
<td>3,843</td>
<td>3,699</td>
<td>3,472</td>
<td>3,551</td>
</tr>
</tbody>
</tbody>
</table>
The output looks like this:
If you do actually want the years labels to be displayed on the y-axis (with horizontal bars, instead of vertical bars) then you can change the chart type by changing this part of the chart...
chart: { type: "column" },
to this:
chart: { type: "bar" },

How to draw google barchart using dynamic data from Json

I am trying to get Json data using the $.getJSON() method.
And this is the result:
Hcount:29Acount:0Pcount:12Ccount:0
I wanted to draw a bar chart using the result count with the help of the google chart API so I used the getbar() method. But nothing happenes after passing the getbar() method.
Here is the Javascript and HTML code:
function getStats() {
var obj1="";
$.getJSON('getbusinessstats', function(response) {
var txnSource = "";
$.each(response.tanSource, function(key, value) {
tanSource += key+":"+value
});
obj1={ "Array1": [tanSource] };
alert(obj1.Array1)
getbar(obj1);
//$('#vis_div tbody').html(tanSource);
});
}
function getbar(obj2)
{
google.load('visualization', '1');
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [obj2],
options: {'title': 'INPUT'},
containerId: 'vis_div'
});
wrapper.draw();
}
}
$(document).ready(function() {
getStats();
setInterval(function() {
getStats();
}, 5000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="lib/jquery-1.11.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div >
<span class="label label-info">INPUT </span>
<table id="vis_div">
<tbody>
</tbody>
</table>
</div>
</body>
</html>

PDF is not rendering properly in Rotativa

This is my page.
#model JNCloud.Web.UI.Models.AppointmentModel
#{
Layout = null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UB-04-081A</title>
<link href="~/Content/agency_media.css" type="text/css" media="all" rel="stylesheet" />
<link href="~/Content/agency_style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="~/Scripts/Common/js/jquery.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.hoverIntent.minified.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.naviDropDown.1.0.js"></script>
<script type="text/javascript" src="../../Scripts/jquery-mask.js"></script>
<script type="text/javascript" src="../../Scripts/telerik.all.min.js"></script>
<script type="text/javascript" src="../../Scripts/scriptbreaker-multiple-accordion-1.js"></script>
<script src="#Url.Content("~/Scripts/jquery.poshytip.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.poshytip.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.poshytip.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/calendar/fullcalendar.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/calendar/overlib.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/calendar/fullcalendar.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/calendar/overlib.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/form.section.validator.js")" type="text/javascript"></script>
<script>window.jQuery || document.write('<script src="scripts/jquery164min.js">\x3C/script>')</script>
<!--local fallback for JQuery-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="~/Scripts/Common/js/qyb8ood.js"></script>
<script type="text/javascript">try { Typekit.load(); } catch (e) { }</script>
<script>window.jQuery || document.write('<script src="scripts/jquery164min.js">\x3C/script>')</script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var arr = new Array();
$(document).ready(function () {
SelectedScheduleEvents('#Model.PrintAgencyUserID', '#Model.PrintFiltervisittypeID', '#Model.PrintPatientID', '#Model.PrinttypeSchedule', '#Model.PrintDate');
});
function SelectedScheduleEvents(agencyuserid, FiltervisittypeID, PatientID, typeSchedule, date) {
console.log('manoj');
$("#calendar").empty();
$("#LocationId").attr('data-val-number', 'Patient Name does not Exists');
var cdate = date.replace('-', ' ');
var d = new Date(cdate);
var m;
var y;
if (isNaN(d.valueOf())) {
d = new Date();
m = d.getMonth();
y = d.getFullYear();
}
else {
m = d.getMonth();
y = d.getFullYear();
}
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next,today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
year: y,
month: m,
agenda: 'h:mm{ - h:mm}',
editable: false,
disableResizing: true,
selectable: true,
selectHelper: true,
select: function (start, end, allDay, Id) {
var Selectedtdate = start;
//alert('start'+start);
var todate = new Date();
//alert('todate'+todate.getMonth()+3);
//if (Selectedtdate > todate && Selectedtdate.getDate() != todate.getDate()) {
//if (Selectedtdate > todate.getMonth()+3 ) {
// alert('Please select less than 90 days later from todate.');
// return;
//}
AddEvent(start);
calendar.fullCalendar('unselect');
},
events: { url: '#Url.Action("SelectedScheduleEvents", "Schedule")' + '?AgencyUsersID=' + agencyuserid + '&FiltervisittypeID=' + 0 + '&PatientID=' + PatientID + '&typeSchedule=' + typeSchedule },
eventClick: function (calEvent, jsEvent, view) {
var eventTime = $.fullCalendar.formatDate(calEvent.start, "h:sstt");
var Id = calEvent.id;
var apptype = calEvent.appointmenttype;
var clinicianId = calEvent.clinicianId;
var startdate = calEvent.start;
var enddate = calEvent.end;
var comment = calEvent.comment;
var meetduration = calEvent.duration;
var backcolor = calEvent.backgroundColor;
var patientIds = calEvent.patientIds;
var locationid = calEvent.locationId;
var lname = calEvent.locationName;
var visittypeid = calEvent.VisitTypeID;
EditEvent(Id, calEvent.title, patientIds, clinicianId, startdate, enddate, eventTime, meetduration, comment, backcolor, apptype, locationid, lname, visittypeid);
},
eventMouseout: function (calEvent, domEvent) {
if (!$("#events-layer").hasClass('mouse_in')) {
$("#events-layer").remove();
}
}
});
$("#divLoading").hide();
$("#hdnCurrentDate").val(0);
}
</script>
</head>
<body style="padding: 0; font-family: Arial, Helvetica, sans-serif;">
<div style="display: none">#Html.TextBoxFor(x => x.SelectedPID)</div>
<div class="widget first">
<div>
<div id="calendar" style="width: 100%;">
</div>
</div>
</div>
#* End Confirm Assessment form *#
</body>
</html>
And in controller when I use this
return View(objappointmentmodel);
then it's look like this
And when in controller I use this
return new ViewAsPdf("PrintCalendar", objappointmentmodel)
{
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Orientation.Portrait,
PageMargins = { Left = 0, Right = 0 }
};
then it's look like this. This isn't loading properly.
What should I do?
I have researched also about this. But I can't find a proper solution.
Please suggest me.
i got similiar problem-
the rotativa didnt manage to handle the font-family.
when i use ARIAL the PDF looks good.
try also to change path to js and css file to a full path.
good luck
I've been using Rototiva recently to make customer print outs on the fly and I've ran into issues regarding relative paths as opposed to fully qualified paths. My strategy was to create a partial view and view model for the parts of my page that required jquery and images (rendered using the #Html.Action() helper) and then make the pdf with two different action results in my controller:
public ActionResult CustPrintOut() {
// doing stuff
return View("CustPrintOut"); // return a view that renders your partials
}
public ActionResult printout() {
return new ActionAsPdf("CustPrintOut") {
FileName = "printout.pdf"
};
}

Displaying data points from server side txt file on google graph

I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc
Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

HighCharts reading from CSV basic example

Am new to highcharts and JS and am trying to plot data from a csv file (data3.csv).
Here is the code at the moment:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Stock Chart'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Price'
}
},
series: []
};
$.get('data3.csv', function(data) {
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
And the contents of the csv file are:
Date Open
29/01/2010 538.49
28/01/2010 544.49
27/01/2010 541.27
26/01/2010 537.97
25/01/2010 546.59
However, this is not giving a chart (just gives the title).
Could anyone suggest where I am going wrong?
Thanks
In line
var items = line.split(',');
You should spline csv by commas, but you have space. So you can replace this line with:
var items = line.split(' ');
or generate csv which items will separated by comma.
As a result your parser should looks like:
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo>0)
{
options.xAxis.categories.push(items[0]); //set first column from CSV as categorie
options.series[0].data.push(parseFloat(items[1])); //set second column from CSV as point value
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});

Categories

Resources