I uploaded the following index.html file for a subdomain and it isn't properly loading. It only shows the title tag.
I want it to load when I go to xxx.myapp.com. The setup is ok on godaddy because I see the title, but the rest of the page doesn't render. Also I see the network requests on the server bit nothing...
Any thoughts?
<!DOCTYPE html>
<html>
<head>
<title>MI Testing title</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://www.myapp.com/JS/HelperFunctions.js"></script>
<script type="text/javascript" src="http://www.myapp.com/JS/Settings.js"></script>
<!-- zurb foundation-->
<link type="text/css" rel="stylesheet" href="http://www.myapp.com/foundation-4.3.1/CSS/foundation.css" />
<link type="text/css" rel="stylesheet" href="http://www.myapp.com/foundation-4.3.1/CSS/foundation.min.css" />
<link type="text/css" rel="stylesheet" href="http://www.myapp.com/foundation-4.3.1/CSS/normalize.css" />
<!--Local css -->
<link type="text/css" rel="stylesheet" href="http://www.myapp.com/CSS/AnalyticsIndex.css"/>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
/*
Called when library loaded
*/
function drawCharts(){
drawDailyAverageSessionLength();
drawUsersGender();
}
/*
Draws the chart for average session length by day
*/
function drawDailyAverageSessionLength() {
//Apit to get the data from
var api = GET_AVG_SESSIONS_URL+"2013/0/0";
//Request data (using jquery/ajax)
$.getJSON(api,function(data){
//Start a days and seconds array
var days = [];
var seconds = [];
//Init google data array
var googData = new google.visualization.DataTable();
//Add X Y columns
googData.addColumn('string', 'days');
googData.addColumn('number', 'seconds');
//Init sort array
var sorted =[];
//Parse the results to get the dates
for (var key in data){
var date = new Date(key);
sorted.push(date);
}
//Sort the array
sorted.sort(sortDateArrayDescending);
//Split results
for (i=0;i<sorted.length;i++){
//Get the date object
var day = sorted[i];
//Add 1 to month
var month = day.getMonth()+1;
//Parse to string
var newKey = day.getFullYear()+'-'+month+'-'+day.getDate();
var short = month+'/'+day.getDate();
//Add date to days array
days.push(short);
//Add to integer array
seconds.push(parseInt(data[newKey]));
}
//Parse to google data
for (i=0; i<days.length;i++){
googData.addRow([days[i], seconds[i]]);
}
// Set chart options
var options = {'title':'Average session length (NOT ACCURATE since end of sessions aren\'t being tracked)',
'width':1200,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('averageSessionLengthChart'));
chart.draw(googData, options);
});
}
/*
Draws the chart for average session length by day
*/
function drawUsersGender() {
//Apit to get the data from
var api = GET_USERS_SEX;
//Request data (using jquery/ajax)
$.getJSON(api,function(data){
//Start a days and seconds array
var result = [['gender', 'number']];
//Iterate over the genders
for (var gender in data){
//Get the value pair and push
var entry = [gender, parseInt(data[gender])];
result.push(entry);
}
//Parse to google data
var data = google.visualization.arrayToDataTable(result);
//Display options
var options = {
title:'Gender for registered users',
'width':600,
'height':400
};
//Draw the chart
var chart = new google.visualization.PieChart(document.getElementById('genderChart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div class="row">
<div id = "averageSessionLengthChart" class="large-12 small-12 columns">
</div>
</div>
<div class="row">
<div id = "genderChart" class="large-12 small-12 columns">
</div>
</div>
</body>
</html>
Try a developper console from a PC outside your network to see what requests are sent (Press 'F12' on chrome or install the firebug extension on Firefox).
There should be a "Network" tab that shows what requests are made from the page.
Maybe it will help you understand what is happening.
Related
On load my web app is producing this error:
DataTables warning: table id=data-table - Requested unknown parameter '9' for row 21, column 9. For more information about this error, please see http://datatables.net/tn/4
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
//GET DATA FROM GOOGLE SHEET AND RETURN AS AN ARRAY
function getData(){
var spreadSheetId = "1VzHY8fTq8OsXhpHYHESSSPxeVNOnqxpjcsyWJpbuEOs"; //CHANGE
var dataRange = "Base Stats!A2:L"; //CHANGE
var range = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
var values = range.values;
return values;
}
//INCLUDE JAVASCRIPT AND CSS FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--INCLUDE REQUIRED EXTERNAL JAVASCRIPT AND CSS LIBRARIES-->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css">
<?!= include('JavaScript'); ?> <!--INCLUDE JavaScript.html FILE-->
</head>
<body>
<div class="container">
<br>
<div class="row">
<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
<!-- TABLE DATA IS ADDED BY THE showData() JAVASCRIPT FUNCTION ABOVE -->
</table>
</div>
</div>
</body>
</html>
JavaScript.html
<script>
/*
*THIS FUNCTION CALLS THE getData() FUNCTION IN THE Code.gs FILE,
*AND PASS RETURNED DATA TO showData() FUNCTION
*/
google.script.run.withSuccessHandler(showData).getData();
//THIS FUNCTION GENERATE THE DATA TABLE FROM THE DATA ARRAY
function showData(dataArray){
$(document).ready(function(){
$('#data-table').DataTable({
data: dataArray,
//CHANGE THE TABLE HEADINGS BELOW TO MATCH WITH YOUR SELECTED DATA RANGE
columns: [
{"title":"Date Added"},
{"title":"SpotRacer"},
{"title":"Brand"},
{"title":"Model"},
{"title":"Acceleration"},
{"title":"Speed (MPH)"},
{"title":"Speed (KPH)"},
{"title":"Handling (%)"},
{"title":"Star Rating"},
{"title":"Comments"},
{"title":"Score (Cumlative)"},
{"title":"Score (Weighted)"}
]
});
});
}
</script>
I'm not sure what is causing the error with that specific row and column, but perhaps has something to do with the column not displaying plain text? Column 9 is 'Star Rating'.
Google Sheet: SpotRacers Fanbase Database
In your script, Sheets.Spreadsheets.Values.get of Sheets API is used. In this case, the retrieved values are 2-dimensional array. But, for example, when all rows are not embedded by the cell values (for example, the 1st row has the values in the columns "A", "B", "C", and the 2nd row has the values in the columns "A" and "B".), the lengths of all rows are different. I'm worried about this situation. So, I thought that the reason for your issue might be due to this.
If my understanding of your current issue was correct, how about the following modification?
From:
function getData(){
var spreadSheetId = "###"; //CHANGE
var dataRange = "Base Stats!A2:L"; //CHANGE
var range = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
var values = range.values;
return values;
}
To:
function getData(){
var spreadSheetId = "###"; // Please set your Spreadsheet ID.
var sheet = SpreadsheetApp.openById(spreadSheetId).getSheetByName("Base Stats");
var values = sheet.getRange("A2:L" + sheet.getLastRow()).getDisplayValues();
return values;
}
In this modification, the values are retrieved using getDisplayValues(). And, the data is retrieved from the data range.
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.
You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
Reference:
getDisplayValues()
I've been working on the Search CRUD using Google WebApp Script via watching a YouTube tutorial, I'm almost done but I'm stuck in a place I couldn't figure out to sort the issue.
I want to load the search field and the data on first page load. but based on this code I need to click on the Search Tab and then get the search field to find the data. How do I get rid of the Search Tab and get straight into the search bar and data.
On Page load
Second Occurrence (After the Click)
My code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
.nav-link {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li class="nav-item">
<div class="nav-link"id="search-link">Search</div>
</li>
</ul>
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
document.getElementById("search-link").addEventListener("click",loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
</script>
</body>
</html>
Server Side Code
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Array");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
I need to type letters in order to data display.
Screen Shot 3
Issue:
There are some actions that are currently happening when the Search tab is clicked.
You want these actions to happen when the page loads.
Solution:
In the HTML you provided, there's a click event listener attached to the Search tab you mention (id="search-link"):
document.getElementById("search-link").addEventListener("click",loadSearchView);
This means the function loadSearchView is gonna execute when the Search tab is clicked.
If I understand you correctly, you want loadSearchView to execute when the page loads. In that case, you could just add the following event listener:
window.addEventListener("load", loadSearchView);
Notes:
Since you didn't provide server-side code, I cannot know whether loadSearchView will do what you intend it to do. This solution just makes sure loadSearchView is executed when the page loads.
If you want to get rid of the Search tab, just remove it from your HTML (<div class="nav-link"id="search-link">Search</div> and its container elements).
Reference:
Window: load event
I have a csv file which i read into a javascript variable. I now try to create a visualization for this.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<link href="http://code.jquery.com/ui/1.9.0/themes/cupertino/jquery-ui.css" rel="stylesheet" />
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script></script>
<script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["motionchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("stockdata.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
However, the second column in the data variable has to be type casted to a date. The string is already in yyyy-mm-dd format but this is not being accepted by the visualization. How can i convert only the second column into date type.
Simply modify your data before visualizing it. The map function will collect every element of an object (or row of your array) and return it as a new array. You will modify each row in place before returning it.
arrayData = arrayData.map(function(row) {
row[1] = new Date(row[1]);
return row;
}
I am currently researching the possibility to grabbing data from the Tableau report(s) via the JavaScript API but the closet I can get to grabbing values from a graph after filtering is selecting the value via the selectSingleValue() method.
For example: JavaScript API Tutorial
In the API tutorial tab called 'Select'. One of the examples selects the row "Marcao Sao, China". Is it possible to extract that numerical value of $52.0k ?
I have tried looking into the Objects returned (via FireBug) but I cannot seem to locate the right object. My recent location was in getActiveSheets().
Any help would be appreciated.
In the JavaScript API tutorial tab 'Events' it shows you how to add an event listener to return the selected marks. You can then loop through the marks to get the values you want.
Copy the below code block into a file, save as html and open in your favourite web browser (tested on ie11).
<html>
<head>
<meta charset="utf-8">
<title>Tableau 8 Javascrip API</title>
<script type="text/javascript" src="http://public.tableausoftware.com/javascripts/api/tableau_v8.js"></script>
<script type="text/javascript">
/////////////////////
// Global variables
var viz, workbook, activeSheet
// function called by viz on marks being selected in the workbook
function onMarksSelection(marksEvent) {
return marksEvent.getMarksAsync().then(reportSelectedMarks);
}
function reportSelectedMarks(marks) {
for (var markIndex = 0; markIndex < marks.length; markIndex++) {
var pairs = marks[markIndex].getPairs();
for (var pairIndex = 0; pairIndex < pairs.length; pairIndex++) {
var pair = pairs[pairIndex];
if (pair.fieldName == "AVG(F: GDP per capita (curr $))") {
alert("You selected a country with an avg GPD per capita of " + pair.formattedValue);
}
}
}
}
// Initialise the viz to hold the workbook
function initializeViz(){
var placeholderDiv = document.getElementById("tableauViz");
var url = "http://public.tableausoftware.com/views/WorldIndicators/GDPpercapita?Region=";
var options = {
width: "800px", //width: placeholderDiv.offsetWidth,
height: "400px", //height: placeholderDiv.offsetHeight,
hideTabs: true,
hideToolbar: true,
onFirstInteractive: function () {
workbook = viz.getWorkbook();
activeSheet = workbook.getActiveSheet();
}
};
viz = new tableauSoftware.Viz(placeholderDiv, url, options);
// Add event listener
viz.addEventListener(tableauSoftware.TableauEventName.MARKS_SELECTION, onMarksSelection);
}
</script>
</head>
<body>
<!-- Tableau view goes here -->
<div id="tableauViz" style="height:1200px; width:1200px"\></div>
<script type='text/javascript'>
//Initialize the viz after the div is created
initializeViz();
</script>
</body>
</html>
Using the example code from the tutorial:
<html>
<head>
<script type="text/javascript"
src="dygraph-combined.js"></script>
</head>
<body>
<div id="graphdiv2"
style="width:500px; height:300px;"></div>
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"temperatures.csv", // path to CSV file
{} // options
);
</script>
</body>
</html>
I'd like to load only the last 10 lines from temperatures.csv instead of the whole file. Can I pass an instruction to the dygraphs' csv parser to do this?
There is no such option to set limit or/and offset according to source code https://github.com/danvk/dygraphs/blob/master/dygraph.js#L2942
But you can override function Dygraph.prototype.parseCSV_ in your code to achieve this.
For example like this:
// Save old function
var parseCSV_ = Dygraph.prototype.parseCSV_;
Dygraph.prototype.parseCSV_ = function(data) {
// Get all data
var ret = parseCSV_(data);
// Return only last 10 items
return ret.slice(ret.length - 10);
};
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"temperatures.csv", // path to CSV file
{} // options
);
P.S. I'd recommend you to use new CSV file with only last 10 items to speed up loading, so generate it on back end if it is possible.