Parsing a button Id to a function - html

I've got a google script that creates a table within a webpage. In that script I'm attempting to create a button that passes it's ID to an HTML function. Here is a code snipit:
if (i != 0){
returnTable = returnTable + "<td><button id="+'"'+data[i][9]+'"'+" onClick="+'"confirm_click(this.id)"'+">Confirm</button></td>";
returnTable = returnTable + "<td><button id="+data[i][9]+" onClick="+'"deny_click(this.id)"'+">Deny</button></td>"
Logger.log("data[i][9] is: " + data[i][9]);
}
Data[i][9] is data(a unique ID Field) that is read from a google spreadsheet. The logger returns the right string, but when the following function is called when the button is clicked the console returns "undefined":
function confirm_click(buttonId){
console.log(buttonID);
}
Any guidance on what I'm doing wrong would be hugely helpful.
Thanks so much,
Loren

function confirm_click(buttonId) <--THIS VAR NAME {
console.log(buttonID) <-- IS NOT THE SAME AS THIS VAR NAME;
}
notice buttonID =/= buttonId. Try making the variable names match and see if the problem persists.

Related

google apps script: get the name of the function that is currently running

I'm trying to get google apps script to log the current function that is running. I have something similar in python like so:
code_obj = sys._getframe(1).f_code
file = os.path.basename(code_obj.co_filename).split('.')[0]
Def = code_obj.co_name
line = str(sys._getframe(1).f_lineno)
try:
Class = get_class_from_frame(sys._getframe(1)).__name__
except:
Class = ''
return "--> " + file + "." + Class + "()." + Def + "()." + line + " --> " + now() + '\n'
Anybody know how to get the name of the current running function?
As in plain JavaScript, you can retrieve current function via arguments.callee, and then retrieve Function's property name:
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function.
function myFunctionName() {
const functionName = arguments.callee.name;
// ...
}
Important note:
Since ES5, arguments.callee is forbidden in strict mode. This can cause an error in cases where the script is using strict mode behind the scenes (see, for example, this):
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
I've noticed this happening, for example, when using default parameters or rest parameters.
Unfortunately, there's not an easy alternative to arguments.callee:
How to get function name in strict mode [proper way]
Get current function name in strict mode
There's a nice way to get all function names and lines called in google-apps-script using:
(new Error()).stack
Please try:
function test() {
console.log(f_(100));
}
function f_(n) {
console.log(stack2lines_((new Error()).stack))
return n + 1;
}
function stack2lines_(stack) {
var re1 = new RegExp('at ([^ ]+) \\(Code\\:(\\d+).*', 'gm');
var re2 = new RegExp('\\{.*\\}', 'gm');
var result = stack
.replace(re1, '{"$1": $2}')
.match(re2);
return result;
}
The result:
[ '{"f_": 6}', '{"test": 2}' ]
Source:
https://script.google.com/u/0/home/projects/1BbaDeja4ObWMwbVnhCJ29FHsNfQm-SfAPYvpqobh2B96TA5449GnGnHc/edit

Trouble Adding Array output to an Dynamically Generated HTML String in GAS Google Script

I am trying to automate my businesses blog. I want to create a dynamic html string to use as a wordpress blog description. I am pulling text data from email body's in my gmail account to use as information. I parse the email body using the first function below.
I have everything working properly except for the for loop (in the second code block) creating the description of the post. I have searched for hours and tried dozens of different techniques but I cant figure it out for the life of me.
Here is how I am reading the text values into an array:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
This is how I am trying to dynamically output the text arrays to create a basic HTML blogpost description (which I pass to xmlrpc to post):
var1 = getMatches(string, regex expression, 1);
var2 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var fulldesc = "<center>";
var text = "";
for (var k=0; k<var1.length; k++) {
text = "<u><b>Var 1:</u></b> " + var1[k] + ", <u><b>Var 2:</u></b> " + var2[k] + ", <u><b>Var 3:</u></b> " + var3[k] + ", <u><b>Var 4:</u></b> " + var4[k] + ", <br><br>";
fulldesc += text;
}
fulldesc += "</center>";
Lastly here is the blog post description code (using GAS XMLRPC library):
var fullBlog = "<b><u>Headline:</u> " + sub + "</b><br><br>" + fulldesc + "<br><br>General Description: " + desc;
var blogPost = {
post_type: 'post',
post_status: 'publish', // Set to draft or publish
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
categories: cat, //cat is defined elsewhere and works fine
date_created_gmt: pubdate2, //defined elsewhere (not working but thats another topic)
mt_allow_comments: 'closed',
description: fullBlog
};
request.addParam(blogPost);
If there's only one value in the var1,2,3,4 arrays all works as it should. But any more than 1 value and I get no output at all from the "fulldesc" var. All other text variables work as they should and the blog still gets posted (just minus some very important information). I'm pretty sure the problem lies in my for loop which adds the HTML description to text var.
Any suggestions would be greatly appreciated, I'm burned out trying to get the answer! I am a self taught programmer (just from reading this forum) so please go easy on me if I missed something stupid :)
Figured it out: It wasnt the html/text loop at all. My blogpost title had to be a variable or text, but not both.
Not working:
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
Working:
var test = 'Ticker: ' + sub;
//
title:test,

Will Javascript read returned string as script or treat it as a string?

I am wondering is it possible to run a function that outputs a line that javascript can read and recognize as a variable and not as a string? I have pulled JSON data and what I want to do is to take the object data and dynamically write out variables from it on the fly. I hope this is possible..
function createVar(data){
return "var_" + data.name + data.id + "=_" + data.desc;
//This will return the line :
var itemModel1 = "I no longer vote";
}
I have to say that I don't really recommend this, but it does work.
function createVar(data){
return "var " + data.name + data.id + "='" + data.desc + "'";
}
var exampleData = {name:"itemModel", id:"1", desc:"Today we went to the mall"}
eval(createVar(exampleData));
console.log(itemModel1); //outputs "Today we went to the mall" to the console
I will clarify by saying that if you actually need to generate variable names on the fly, this will do the trick. But I would more closely examine your code to see if there is another way to accomplish what you are trying to do. As always, you have to be very careful with eval, bad things can happen if user input gets passed as your data parameter.

Google Docs Script Issue with Split through Function

First time poster here for Google Script related services, hopefully I put it in the right place! I'm encountering an error and I can't seem to find the right terminology to look up a solution. Below is the function. Within it I have a variable, string1, that I apply the split to. If I hard-code the value of the string (in the line commented out in the string), then it works and I receive the correct output. If, on the other hand, I try to pass that string into the function from another function, I receive the following error:
"TypeError: Cannot find function split in object Wed Oct 30 2013 09:00:26 GMT-0400 (EDT),danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found."
Note: My call to the function looks like this - formatEmailRow(completeEmailArray[i])
function formatEmailRow(rowToFormat) {
var formattedString = "";
var array1 = [];
var string1 = "";
///////////////////////
string1 = rowToFormat;
//string1 ="10/30/2013 9:00:26,danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found ";
///////////////////////
array1 = string1.split(",| ,|, ");
if (array1 != ""){
for (var i = 0; i < array1.length; i++) {
formattedString = formattedString + " " +(array1[i]);
}}
return formattedString;
}
Please help!
Thanks ahead of time, any advice is appreciated!
-Danno
You're getting that error because .split() isn't a method contained in the type of object you've passed in. Since you're new to this, it's worth a pause to read up on Objects and Methods - this is a quick overview.
You want to receive a String, but it seems that you're not. The problem will be with the code that's calling formatEmailRow().
My guess is that you're passing an array - probably all the cells in a row - but here's how you can check.
Add this line as the first line in your function:
Logger.log("rowToFormat = " + JSON.stringify(rowToFormat));
... then run, with your error. Check the logs - you want to see that you are getting a simple string. If you're getting an array, then you know what you need to fix. (Maybe you want to get the array after all!)

HTML5 - Javascript Sqlite nested transactions

this is my first post here, I'm glade to hear from you :-)
Here's my question, please.
In my JqueryMobile web application I've created categories and records.
Each category hosts different records.
What I'd like to print out to the user is the number of records that exists in each category.
For selecting the categories I made a normal transaction
function getAll() {
db.transaction(function (transaction) {
transaction.executeSql(("SELECT * FROM tags"), [], getAllSuccess, errorCB);
});
}
function getAllSuccess(tx, result) {
$('#bags_ul').empty();
var output = '';
$.each(result.rows, function (index) {
var row = result.rows.item(index);
output += '<li><a href="#" class="link_to_tag" data-tagnome="' + row['tagnome'] + '" data-tagtipo="' + row['tagtipo'] + '" data-tagid="' + row['tagid'] + '" >' + row['tagnome'] + '</a></li>';
});
$('#bags_ul').html(output);
$('#bags_ul').listview();
$('#bags_ul').listview('refresh');
}
In my example, the function getAll makes the query, and if get success it execute the getAllSuccess function, that fills in the LI fields of my list.
The problem is that I need to create a query inside the $.each() to get the records of the category.
I've tried to execute another transaction within it, and I can successfully get the number of records thorugh the console.log function, but the problem is that I don't know how to pass it to the "mother" function that in facts pushes the HTML to the page.
Could you please help me?
As you have understood, I need to know the "logic" that is behind this.
I really do thank you very much for your help.
Marco
You could chain the callbacks yourself or use JQuery Deferred.