Fix on_click function to change text - javascript

When I click on a button, a function is run. This function generates a string, and I am trying to display this string to the user in the div tag.
I tried to debug this in a few ways. For example, I check that the onclick is working. So, when I click the button, I do see "Clicked!" and then "In Function". This is expected. However, after that, it is supposed to display the string generated by the listAllEvents function. However, it does not seem to be working properly. (It logs the result as expected; it just doesn't display on the screen.)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function myFunction() {
document.getElementById("data").innerHTML = "Clicked!";
listAllEvents()
}
function listAllEvents() {
document.getElementById("data").innerHTML = "In Function!";
var calendarId = 'primary';
var now = new Date();
var display = ""
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
maxResults: 2500,
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
var end = new Date(event.end.date);
display = display + 'Start: ' + start.toLocaleDateString() + '; End: ' + end.toLocaleDateString() + ". ";
} else {
var start = new Date(event.start.dateTime);
var end = new Date(event.end.dateTime);
display = display + 'Start: ' + start.toLocaleString() + '; End: ' + end.toLocaleString() + ". ";
}
}
} else {
display = 'No events found.';
}
Logger.log('%s ', display);
document.getElementById("data").innerHTML = "Almost There";
document.getElementById("data").innerHTML = display;
}
</script>
<div id="data"> Hello! </div>
<button onclick="myFunction()">Run Function</button>
Expected, on click: Start....End.
Actual: "In Function!"

Can't use server side code on the client
The problem is that your trying to run server side code on the client.
function listAllEvents() {
document.getElementById("data").innerHTML = "In Function!";
var calendarId = 'primary';
var now = new Date();
var display = ""
var events = Calendar.Events.list(calendarId, {//This is server side Google Script
timeMin: now.toISOString(),
maxResults: 2500,
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
var end = new Date(event.end.date);
display = display + 'Start: ' + start.toLocaleDateString() + '; End: ' + end.toLocaleDateString() + ". ";
} else {
var start = new Date(event.start.dateTime);
var end = new Date(event.end.dateTime);
display = display + 'Start: ' + start.toLocaleString() + '; End: ' + end.toLocaleString() + ". ";
}
}
} else {
display = 'No events found.';
}
Logger.log('%s ', display);
document.getElementById("data").innerHTML = "Almost There";
document.getElementById("data").innerHTML = display;
}
When you want to run server side google script you can call them with google.script.run
Here's a simple example of how to use google.script.run
This is the basic frame work:
Your html file:
The button click calls the Javascript function getCalendarEvents which prepares the appropriate (probably not required in this case) data to pass to the server and then it calls listCalendarEvents which is on the server. The server function gets the events and returns them to the withSuccessHandler and that handler then puts the information into the html page.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function getCalendarEvents() {
google.script.run
.withSuccessHandler(function(eObj){
//load html with data from eObj
})
.listCalendarEvents();
}
function listAllEvents() {
}
</script>
<div id="data"> Hello! </div>
<button onclick="getCalendarEvents();">Run Function</button>
code.js:
function listCalendarEvents() {
//get all of the events
return eObj;
}

It crashes because Calendar is undefined. Your browser's console will tell you.

Related

Failed to parse Json into Html via JavaScript

I have the following JavaScript function that is called onload of an HTML page, but my data isn't parsing nor anything can be written in html through this function:
function displaySearchResults(){
//link base para a realização de requests para a API
var requestBaseURL = "https://api.predicthq.com/v1/events?";
var startDate = "start.gte=" + sessionStorage.getItem("startDate") + "&";
var endDate = "start.lte=" + sessionStorage.getItem("endDate") + "&";
var eventType = "category=" + sessionStorage.getItem("eventType") + "&";
var countrySearch = "country=" + sessionStorage.getItem("countrySearch");
var requestURL = requestBaseURL + startDate + endDate + eventType + countrySearch;
var searchRequest = new XMLHttpRequest();
searchRequest.withCredentials = false;
searchRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
var data = JSON.parse(this.responseText);
console.log(data);
//TODO parse data into lists with associated buttons
var result = data.results
var msg = ""
for (var i=0;i < result.length;i++) {
msg += ("<li>" + result[i].title + "</li>\n");
}
msg = "<li>END</li>"
document.getElementsById("searchResults").innerHTML=msg;
}
});
}
Nor any data from the request nor de END msg is passing to the this HTML page:
(...)
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="displaySearchResults()">
<header id="header">
</header>
<div class="container">
<div class="row">
<h5>Resultados:</h5>
<ul id="searchResults">
</ul>
</div>
</div>
</body>
Ive tried calling it at the end and after the body tag, same result. If its on load why doesn't appear anything, also console shows no errors.
Try this. It has a button which on click render the List in dom.
var data = {
results: [{
title: "title1"
}, {
title: "title2"
}, {
title: "title3"
}]
}
function LoadResult() {
var result = data.results
var msg = "<ul>"
result.forEach(s => {
msg = msg + "<li>" + s.title + "</li>"
})
msg = msg + "<li>END</li></ul>"
document.getElementById("result").innerHTML = msg;
}
<html>
<body>
<button onClick="LoadResult()">Load</button>
<div id="result">
</div>
</body>
</html>

How to render multiple html lists with AppScrip?

I am new to the world of * AppScript * I am currently designing a ** WepApp ** which is made up of html lists that connect to Mysql, when I individually test my lists paint correctly and their icons modify and update the data, without However ** the problem is ** when I join all my lists and call them through their corresponding url only the last one paints me the others are blank. For example of 10 lists I call # 2 the log tells me to call 10; I call 5 the same thing happens and if I call 10 it paints the data and they are allowed to be modified.
Within what I have searched I find that my problem lies in the way I render my pages but I cannot find the right path, so I ask for your support.
function doGet(e) {
var template ;
var view = e.parameters.v;
if(view == null){
template = HtmlService.createTemplateFromFile("Index");
}if(view == "Index"){
template = HtmlService.createTemplateFromFile("Index");
}if(view != null && view != "Index"){
template = HtmlService.createTemplateFromFile(view);
}
return template.evaluate()
.setTitle('Documental')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getTemplate(view){
return HtmlService.createTemplateFromFile(view);
}
and with this JavaScript method I connect my appscript code to pass it to my html
window.onload = function () {
google.script.run
.withSuccessHandler(run_This_On_Success)
.withFailureHandler(onFailure)
.readAreaPRE();
};
function onFailure(error) {
var div = document.getElementById("output");
div.innerHTML = "ERROR: " + error.message;
}
function run_This_On_Success (readAreaPRE) {
let table = $("#selectTable");
table.find("tbody tr").remove();
table.append("<tr><td>" + "</td><td>" + "</td></tr>");
readAreaPRE.forEach(function (e1, readAreaPRE) {
table.append(
"<tr><td>" +
e1[0] +
"</td><td>" +
e1[1] +
"</td><td>" +
"<p><a class='modal-trigger' id=" + e1[0] + " href='#modal1' onclick='capturaid("+e1[0]+",'"+ e1[1]+"')'><i class='material-icons'>edit</i></a>" +
"<a class='modal-trigger' href='#modal3' onclick='capturaidsup("+e1[0]+")'><i class='material-icons'>delete</i></a></p>" +
"</td></tr>"
);
});
};
function capturaidsup(dato1){
$("#delAreaPRE").val(dato1)
}
function capturaid(item1,item2) {
$("#uptAreaPRE1").val(item1);
$("#uptAreaPRE2").val(item2);
}
here is my function: readArePRE
function readAreaPRE() {
var conn = Jdbc.getCloudSqlConnection(url, user, contra);
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery(
"CALL `BD_CENDOC_COL`.`sp_lee_tb_ref_AreasPRE`()"
);
var numCols = results.getMetaData().getColumnCount();
var rowString = new Array(results.length);
var i = 0;
while (results.next()) {
var id_areaPRE = results.getInt("id_areaPRE");
var AreaPRE = results.getString("AreaPRE");
rowString[i] = new Array(numCols);
rowString[i][0] = id_areaPRE;
rowString[i][1] = AreaPRE;
i++;
}
return rowString;
conn.close();
results.close();
}
Thank you in advance, any correction to ask my question will be welcome.

Javascript initially skipping over nested function and then comes back to it?

I'm experiencing some weird behavior in my code that I don't quite understand. I call a function, and inside that function there is another (anonymous) callback function it skips over and it goes to the end of the containing function, runs those lines, and then goes back into the callback function and runs those lines... Anybody have some insight, what am I doing wrong? Is it doing this because the "relatedQuery" method isn't complete yet so it hasn't hit the callback function before it runs the rest of the containing function's lines? That's the only thing I can think of, but I'm also not very skilled at JS. I've added some console.log statements that will tell you the order in which lines are being hit.
//Call the mgmtPopupContent function
mgmtTractPopupBox.setContent(mgmtPopupContent);
function mgmtPopupContent(feature) {
for (var attrb in feature.attributes) {
if (attrb == "HabitatManagement.DBO.MgmtTracts.OBJECTID") {
var OID = feature.attributes[attrb];
}
}
var relatedQuery = new RelationshipQuery();
relatedQuery.outFields = ["*"];
relatedQuery.relationshipId = 0;
relatedQuery.objectIds = [OID];
//Get data year that the map view is set to and set the definition expression on the table
viewYear = dom.byId("data-year").value;
relatedQuery.definitionExpression = "YearTreated = " + viewYear;
//Create table header that will go inside popup
var content = '<table id="mgmtPopupTable1"><tr><th>Veg Mgmt Practice</th><th>Herbicide</th><th>Month</th><th>Year</th>\
<th>Implemented By</th><th>Funded By</th><th>Farm Bill Code</th></tr>';
console.log("PRINTS FIRST");
//Do query and get the attributes of each related record for the popup
queryableMgmtTractFL.queryRelatedFeatures(relatedQuery, function (relatedRecords) {
console.log("PRINTS THIRD");
var fset = relatedRecords[OID].features;
fset.forEach(function (feature) {
var vegPractice = vegPName(feature.attributes.VegMgmtPractice);
var herbicide = herbName(feature.attributes.Herbicide);
var monthTreated = monthName(feature.attributes.MonthTreated);
var yearTreated = feature.attributes.YearTreated;
var impBy = impName(feature.attributes.ImplementedBy);
var fundBy = fundName(feature.attributes.FundedBy);
var fbc = feature.attributes.FarmBillCode;
if (fundBy == "CRP" || fundBy == "CRP - CREP") {
fbc = crpName(fbc);
}
else if (fundBy == "EQIP" || fundBy == "EQIP - RCPP") {
fbc = eqipName(fbc);
}
else {
fbc = "Not applicable";
}
row = '<tr><td>' + vegPractice + '</td><td>' + herbicide + '</td><td>' + monthTreated + '</td><td>' + yearTreated +
'</td><td>' + impBy + '</td><td>' + fundBy + '</td><td>' + fbc + '</td></tr>';
content = content + row;
});
content = content + '</table>';
});
console.log("PRINTS SECOND");
return content;
}
As mentioned in my comment, you have to wait for the queries to finish before you can render the content. So something like:
let content = '<table id="mgmtPopupTable1"><tr><th>Veg Mgmt Practice</th><th>Herbicide</th><th>Month</th><th>Year</th>\
<th>Implemented By</th><th>Funded By</th><th>Farm Bill Code</th></tr>';
const render_popup = function( content ) {
document.querySelector( '#myPopup' ).innerHTML = content;
};
// Render only the headers to begin with.
render_popup( content );
queryableMgmtTractFL.queryRelatedFeatures(relatedQuery, function (relatedRecords) {
var fset = relatedRecords[OID].features;
fset.forEach(function (feature) {
...
});
// Rerender the popup, now headers And content.
render_popup( content );
});

Javascript How to SetTimeOut while getting a list of files with Scripting.FileSystemObject

This code is for internal, offline, single user use, IE only. The code looks at a folder, and lists all files including those in subfolders. It sorts through the data based on some date fields and datelastmodified. It also uses and if to throw out thumbs.db entries. All of the data is put into a table.
My issue is that this script can take a long time to get the data. I would like to add a progress bar but the progress bar cant update while the script is running. After some research it looks like SetTimeOut can allow the page elements to be updated as the script runs, therefore allowing the progress bar to work and looking overall cleaner. However I can not figure out of to implement SetTimeOut into my existing code.
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
function ShowFolderFileList(folderspec) {
var beginningdate = new Date(startdate.value);
var finishdate = new Date(enddate.value);
var s = "";
var f = fso.GetFolder(folderspec);
var subfolders = new Enumerator(f.SubFolders);
for (subfolders.moveFirst(); !subfolders.atEnd(); subfolders.moveNext()) {
s += ShowFolderFileList(subfolders.item().path);
}
// display all file path names.
var fc = new Enumerator(f.files);
for (i = 0; !fc.atEnd(); fc.moveNext()) {
if (fc.item().name != "Thumbs.db") {
var dateModified = fc.item().DatelastModified;
if (dateModified >= beginningdate && dateModified <= finishdate) {
Date.prototype.toDateString = function () {
return [this.getMonth() + 1, '/', this.getDate(), '/', this.getFullYear()].join('');
}
var dateModifiedClean = (new Date(fc.item().DatelastModified).toDateString());
s += "<table border=0 width=100% cellspacing=0><tr " + ((i % 2) ? "" : "bgcolor=#EBF1DE") + "><td width=75%><font class=find><b>" + fc.item().ParentFolder.name + "</b>" + " - " + fc.item().name + "</font></td><td width=25% align=right><font class=find>" + dateModifiedClean + "</font></td></tr>";
i++;
}
}
}
var results = s + "</table>";
return results;
}
function listFiles() {
outPut.innerHTML = ShowFolderFileList('*Path to scan*');
}
</script>
outPut is the ID of a div tag where the results table is displayed. A button calls the listfiles function.

google visualization multiple charts with own data queries

On my Google Visualization web page I want both a bar chart and an area chart but I can get only one or the other to display.
Each chart requires its own data and employs its own google.visualization.Query object against my own Python-based server. My initialize function calls the function to display the first chart, and at the bottom of the query response handler for the first chart, I'm calling the function to display the second chart. (I am doing this to make sure my second data query does not start until after the first chart is done drawing.) Each chart displays correctly when I code to draw only one chart at a time. But when I try to draw both charts, only the first chart ever draws even though I am verifying that both data queries are running and returning valid json responses, at the correct times.
Thanks for any help, BH
Edit 10/27/2013:
This post solved my problem:
Google Charts - "Missing Query for request id: 0"
To anyone implementing a Python data source, parse the reqId parameter like this:
import cgi
form = cgi.FieldStorage()
tqx = form.getvalue("tqx") # tqx comes back like "reqId:1"
req_id = int(tqx[tqx.find("reqId"): ].split(":")[1])
And pass it to the ToJSonResponse call:
response = data_table.ToJSonResponse(req_id=req_id,
columns_order=("vehicle_id", "num_events"))
print "Content-type: text/plain"
print
print response
Here is my updated code, which also uses the "ready" event.
<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(initialize);
var timelineDate1 = "";
var messageCountsDate1 = "";
var timeline_drawn = false;
var message_count_drawn = false;
function initialize()
{
drawTimeline();
}
function drawTimeline()
{
var rows = QueryString.rows || "4";
var date1 = QueryString.date1 || "2013-9-1"; // Date start
timelineDate1 = date1;
var page = parseInt(QueryString.page) || 1;
if (page < 1)
{
page = 1;
}
// Timeline
var url_timeline = "http://localhost/emit_event_timeline.py"
+ "?date1=" + date1 + "&rows=" + rows + "&page=" + page;
var query_timeline = new google.visualization.Query(url_timeline);
query_timeline.setTimeout(14400);
query_timeline.send(handleTimelineQueryResponse);
}
function handleTimelineQueryResponse(response)
{
var stack = parseInt(QueryString.stack) || 1
var timeline_options =
{
title: 'Event Count Timeline, ' + timelineDate1 + ' to Present',
vAxis: {title: 'Date', titleTextStyle: {color: 'red'}},
hAxis: {title: 'Event Count', titleTextStyle: {color: 'blue'}},
isStacked: stack
};
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var timeline_data_table = response.getDataTable();
var timeline_chart = new google.visualization.AreaChart(document.getElementById('timeline_div'));
google.visualization.events.addListener(timeline_chart, 'ready', timeline_chart_ready);
google.visualization.events.addListener(timeline_chart, 'error', errorHandler);
timeline_chart.draw(timeline_data_table, timeline_options);
}
function timeline_chart_ready()
{
timeline_drawn = true;
if (!message_count_drawn)
{
drawMessagecounts();
}
}
function mc_chart_ready()
{
message_count_drawn = true;
if (!timeline_drawn)
{
drawTimeline();
}
}
function drawMessagecounts()
{
var rows = QueryString.rows || "20";
var date1 = QueryString.date1 || "2013-9-1"; // Date start
messageCountsDate1 = date1
var page = parseInt(QueryString.page) || 1;
if (page < 1)
{
page = 1;
}
// Message counts
var url_message_counts = "http://localhost/emit_all_message_counts.py"
+ "?date1=" + date1 + "&page=" + page + "&rows=" + rows;
var query_message_counts = new google.visualization.Query(url_message_counts)
query_message_counts.setTimeout(14400);
query_message_counts.send(handleMessageCountQueryResponse);
}
function handleMessageCountQueryResponse(response)
{
var stack = parseInt(QueryString.stack) || 1
var mc_options =
{
title: 'Message Counts, ' + messageCountsDate1 + ' to Present',
vAxis: {title: 'Message Source', titleTextStyle: {color: 'red'}},
hAxis: {title: 'Message Count', titleTextStyle: {color: 'blue'}},
isStacked: stack
};
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var mc_data_table = response.getDataTable();
var mc_chart = new google.visualization.BarChart(document.getElementById('message_count_div'));
google.visualization.events.addListener(mc_chart, 'ready', mc_chart_ready);
google.visualization.events.addListener(mc_chart, 'error', errorHandler);
mc_chart.draw(mc_data_table, mc_options);
}
// Thanks to:
// https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
var QueryString = function ()
{
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
function errorHandler(e)
{
// Called when an error occurs during chart processing
alert('Error handler: ' + e.message);
}
</script>
</head>
<body>
<div id="timeline_div" style="width:800px;height:500px;border:1px solid gray;float:left">
</div>
<div id="message_count_div" style="width:800px;height:500px;border:1px solid gray;float:left">
</div>
<div id="control_div" style="width:80px;height:60px;float:left">
</div>
</body>
</html>
The solution was for my Python data source to pass the reqId parameter from the request back on the json reqponse. This post solved my problem:
Google Charts - "Missing Query for request id: 0"

Categories

Resources