HTML Function displaying as plain text - javascript

I have been working on this for quite some time, and have basically been teaching myself HTML, so I apologize if the code is sloppy or if this is a simple fix. Here is what I am attempting to do, and the problem I am running into:
Take Google Form responses, generate an email based on those responses and dynamically email a certain person in my organization based on the location response(this part is done and working, just adding for context). Then create a survey response that sends info back to the original responder, sent from the administrator that the form was sent to. This is the js that I have running, that is working when it is ran in the google project:
function getid() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/a/raytownschools.org/spreadsheets/d/1YWHu_yKn5bqq63x1A4e4-vBUtZANj-xjeF07IBpHP64/edit?usp=sharing');
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
var sheet = spreadsheet.getActiveSheet();
var lastRow = sheet.getLastRow();
}
When I attempt to run that in my HTML code, and insert it into the element, it is simply inserting that code as raw text. HTML isn't running the function, or returning the data that it should be (and does return when ran outside the HTML code as a js app).
I can post the full HTML code if that would be helpful. Hopefully someone on here can help me out.

What you have there is a Javascript function. There aren't functions in HTML, HTML is a markup language.
You must add that function inside Javascript tags like this:
<script type="text/javascript">
function getid() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/a/raytownschools.org/spreadsheets/d/1YWHu_yKn5bqq63x1A4e4-vBUtZANj-xjeF07IBpHP64/edit?usp=sharing');
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
var sheet = spreadsheet.getActiveSheet();
var lastRow = sheet.getLastRow();
}
alert( getid() );
</script>
Take a look at here, on how to use javascript.
Edit
Seems like that code you're trying to execute is for Google Apps Script. I think you must execute it inside the Google script editor, because they don't make this API available for regular websites. Here is a running example with your code.

Related

google script to add information to sheet , script and bootstrap form using showModalDialog

I already have the html form made from bootstrap, however, when I am trying to use the click button to add the information to google sheet from the html form it is not working
this is my GS function
function addRow(rowData){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("STUDENTS");
ws.appendRow([rowData.names,rowData.phones,rowData.idnumber,rowData.fivehr]);
and this is my function on html file
function afterButtonClick(){
var name = document.getElementById("studentnames");
var phone = document.getElementById("phonenumber");
var idnumber = document.getElementById("ID-number");
var fivehr = document.getElementById("fivehr");
var rowData = {name: name.value,phone: phone.value, idnumber: idnumber.value, fivehr: fivehr.value};
google.script.run.addRow(rowData);
}
document.getElementById("ADD").addEvenListener("click",afterButtonClick);
example for the line for the variable
<input style="font-weight:bold" type="text" class="form-control" placeholder="Student Name" aria-label="Name" id="studentnames">
the html form is perfect the way I want it, but the function on html is not adding the data to sheet
I am following a youtuber but it is not working at all, I did some changes on the wording but I guess I am missing something, if anyone can look at it and tell me my mistake, I appreciate the help thank you
if fivehr is a datetime then that is a restricted parameter and cannot be passed using google.script.run. If it is a restricted parameter then the entire object will be nulled out. Read about it below:
https://developers.google.com/apps-script/guides/html/communication#parameters_and_return_values
Keys of your object should be same.
You've to use rowData.name and rowData.phone.
ws.appendRow([rowData.name,rowData.phone,rowData.idnumber,rowData.fivehr]);
In order to see what is the problem, you can firstly go to DevTools > Console and see if there is an error message in your client side functions. If not you go to Script Editor > Executions and see if your server side functions returned an exception.

Google Sheets "Script Function Could Not Be Found"

First time posting here and a newbie at javascript, so hoping this is a very simple fix. I have created an appendRow script (after following a few different examples and amending them for my use). The intention is to have 4 cells at the top of a Google Sheet that are automatically added to the bottom of data in columns A, B, C & D.
Code:
var headers = ['Today' , 'Month' , 'Total Value' , 'Cash Invested'];
var data1 = ['Today' , 'Month' , 'Total Value' , 'Cash Invested'];
var data = [headers , data1];
function putMultipleValues()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("VG Investment Value");
sheet.appendRow(['=a5','=b5','=c5','=d5']);
}
All is working ok, except that the only way I have found to connect the button to the script is by using the 'Select function' name "putMultipleValues". If I use the name of the script (that I have given it) - "VG Table", a "script could not be found" error shows.
This would not be an issue, except I would like to use an almost identical script on a different, almost identical, sheet. The trouble is that this new script also has the 'Select function' name "putMultipleValues" so both scripts fail.
Does anyone know how to change the button so that it links to the script's name rather than it's function?
Many thanks in advance.
Hi and welcome Markrc !
I don't have much experience in Google Script, but from what I understood, a Spreadsheet (and its sheets) is connected to a Script Project.
This Script Project can contains one or more script files.
Each Script files can one or more functions.
The function is what Google Sheet will call a script. (I know, this is a bit confusing)
You can link a script to a button, wich means you can link a function.
However, if you use global variables in your script, the function can access to it (as you noticed). You can link different buttons to different scripts (functions), but you can not link a button to a Script Project or a Script File.
I am not 100% sur of this, but this is how I think it works. If anyone could confirm it, it would be great.
Hope it helped !

Google Apps Script Bad Value

I'm getting a "bad value on line 4"... I don't know why. I'm trying to make a Google sheet that automatically opens to an assigned tab based on gmail address for a large team. Please help!
function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice(0,-9);
var ss = SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}
I suspect here your issue is a misunderstanding of the function '.openById()'.
This function is designed so that you identify and open the spreadsheet using a spreadsheet ID (The alphanumeric part of the URL when opening a sheet, such as "abc1234567"). From context and your use of the variable 'username', I think that instead you're somehow trying to open it based on an email ID (Such as user#domain.com).
Incidentally, you won't be able to open the sheet in an assigned tab using Scripts. That's not what it does, and it's unable to manipulate a users browser. Perhaps an extension for Chrome would be closer to what you're looking for.

Accessing headers of a google spreadsheet using HTTP GET and Google App Script

I'm trying to return the header row of a Google spreadsheet using doGet() in a Google App Script that's running as a WebApp. I'm using a HTML form to send the GET request to the WebApp and it's all working except I don't know how to return the headers to my javascript. I'll post my code:
HTML:
<form id="getForm" method="get" action="My URL for WebApp">
<label for="sheetGetID">SheetID</label>
<input type="text" name="sheetGetID" id="sheetGetID" value="">
<button class="ui-btn" onclick='submitGET()'>Submit</button>
</form>
Javascript:
function submitGET() {
var headers = $("getForm").submit();
alert(headers);
}
Google App Script:
function doGet(e) {
//Trying To: Get headers from sheetID and then return to app, then have correct labels for the inputs, then use POST to post.
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName(e.parameter["sheetGetID"]);
//Return the first 3 cells, A1:C1,
var headers = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0];
return ContentService.createTextOutput(JSON.stringify(headers))
.setMimeType(ContentService.MimeType.JSON);
}
I'm getting a JSON object returned but it's just a text output. My question is how would/could I get the JSON returned and stored as the headers variable?
The return of doGet method must be an HTML.
Build another html page and use the call HtmlService.createTemplateFromFile('newPag.html').evaluate()
Inside your page use the tags and put your server side code manipulating the json object. This way you will create a good look and feel and a good maintanable code.
I got this to work a while ago, I forgot to post the answer just in case anyone else needed it.
You need to output it as a JSON object like the API demo. You also need to append "?prefix=?" to the url when you're doing a $.getJSON() call. The prefix part is to tell the JQuery that it is a JSON object you're receiving.
If anyone has troubles with this just comment and this and I'll post all the code I used.
So on your client end, I'm using JQuery Mobile, I'm not sure how to do it without it, you would do something like:
sheetID = $("#sheetGetID").val();
$.getJSON("https://script.google.com/macros/s/YOUR_KEY_GOES_HERE/exec?prefix=?",
{ sheetGetID: sheetID},
function(results) {
var fields = results.split(",");
//Do something with fields
}
);
}
Where #sheetGetID is the textbox where the user can enter the sheet id for headers.
Note the ?prefix=? appended to the URL, that part is for JQuery to know it's receiving JSON. That part is necessary. The URL is your deployed WebApp.
On the Google App Script side, ie Server side, you'd have something like:
function doGet(request) {
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName(request.parameter["sheetGetID"]);
//Return the first 3 cells, A1:C1,
var headers = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0];
var result = headers.join();
var content = request.parameters.prefix + '(' +JSON.stringify(result) + ')';
return ContentService.createTextOutput(content)
.setMimeType(ContentService.MimeType.JSON);
}
If you have any questions on how the spreadsheet part works theres plenty of documentation on Google's API's. doGet() is called when you use the $.getJSON(), the return from the G.A.S. needs to be JSON. Most of this is covered in the documentation Google has, some of it I found watching Google Developers Live on youtube. If you are trying to do more stuff I highly recommend checking those sources out.
If you have any more questions about what's being called or parameters you can find it easily enough on Google.

How to Call Google Apps Script from Web Page

Have searched high and low for this. I have a web page of basic HTML/CSS/JS. I want users to be able to visit the page and upon opening page, a call is made to a google script I made which takes information from a spreadsheet and displays some of it on the page. I am hoping I don't have to do any fancy set up like in Google's tutorials because none of them were helpful to me.
My Webpage ----> Google Script ----> Google Spreadsheet
My Webpage <---- Google Script <---- Google Spreadsheet
Users should be able to select an item shown on the webpage (item populated from spreadsheet) and click a button which will allow users to enter a new page with a URL derived from the selected item.
This is essentially a chat room program where the chat rooms are stored on a spreadsheet. I want users to be able to create a new chat room as well which should update the google spreadsheet.
Look into using the GET parameters. https://stackoverflow.com/a/14736926/2048063.
Here's a previous question on the topic.
You can access the parameters passed by GET in your doGet(e) function using e.parameter. If you call http://script.google......./exec?method=doSomething, then
function doGet(e) {
Logger.log(e.parameter.method);
}
doSomething will be written to the log, in this case.
Returning data from the script can be done using the ContentService, which allows you to serve JSON (I recommend). JSON is easiest (in my opinion) to make on the GAS end, as well as use on the client end.
The initial "populate list" call would look something like this. I will write it in jQuery because I feel that is very clean.
var SCRIPT_URL = "http://script.google.com/[....PUT YOUR SCRIPT URL HERE....]/exec";
$(document).ready(function() {
$.getJSON(SCRIPT_URL+"?callback=?",
{method:"populate_list"},
function (data) {
alert(JSON.stringify(data));
});
});
And the corresponding GAS that produces this.
function doGet(e) {
if (e.parameter.method=="populate_list") {
var v = {cat:true,dog:false,meow:[1,2,3,4,5,6,4]}; //could be any value that you want to return
return ContentService.createTextOutput(e.parameter.callback + "(" + JSON.stringify(v) + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
}
This method is called JSONP, and it is supported by jQuery. jQuery recognizes it when you put the ?callback=? after your URL. It wraps your output in a callback function, which allows that function to be run on your site with the data as an argument. In this case, the callback function is the one defined in the line that reads function (data) {.

Categories