Google Script Triggered by Form Submit Sometimes Doesn't Work - javascript

I have a script that reads answers from a Google form when it is sent. The script is bound to a spreadsheet, that captures all answers. The script generates a PDF with some information and sends it to a user via GmailApp, and stores the PDF inside a Drive folder. But sometimes the script doesn't work. The answers are always stored in the spreadsheet, but despite this, the script doesn't run. I have checked the "Execution transcript", but it contains information about the last successful execution.
How can I guarantee that the script always runs?
Can anyone explain why this happens?
Code
//ID del template
var docTemplate = "Template ID Here";
//Nombre de la copia
var docName = "biovenCIP";
//FUnción principal para generación y envío de constancia
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
var registration_date = e.values[0];
var first_name = e.values[1];
var second_name = e.values[2];
var first_lastname = e.values[3];
var second_lastname = e.values[4];
var document_type = e.values[5];
var document_number = e.values[6];
var email_address = e.values[7];
var occupation = e.values[8];
var category = e.values[9];
var payment_number = e.values[10];
var payment_date = e.values[11];
//Inicializando mensaje opcional
var occupation_message = " ";
//Generando el nombre completo
if(second_name.localeCompare("") != 0){
second_name = " " + second_name;
}
if(second_lastname.localeCompare("") != 0){
second_lastname = " " + second_lastname;
}
var full_name = first_name + second_name + " " + first_lastname + second_lastname;
full_name = full_name.replace(/\s+/g," ");
//Generando compia del template
var copyID = DocsList.getFileById(docTemplate).makeCopy(docName + '_' + document_number).getId();
var copyDoc = DocumentApp.openById(copyID);
var copyBody = copyDoc.getActiveSection();
//Reemplazando texto en el template
copyBody.replaceText('keyDate', registration_date);
copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyIDType', document_type);
copyBody.replaceText('keyIDNumber', document_number);
copyBody.replaceText('keyEmail', email_address);
copyBody.replaceText('keyOccupation', occupation);
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 150.00;
break
case "Profesional":
var payment_worth = 200.00;
break
}
copyBody.replaceText('keyOMessage', occupation_message);
copyBody.replaceText('keyCategory', category);
copyBody.replaceText('keyPaymentNum', payment_number);
copyBody.replaceText('keyPaymentDate', payment_date);
copyBody.replaceText('keyPayment', payment_worth)
copyDoc.saveAndClose();
//Convertir temporalmente a PDF
var pdf = DocsList.getFileById(copyID).getAs("application/pdf");
//Adjuntando PDF y enviado correo electrónico
var reply_email = "info#bioven.org.ve";
var bcc_email = "congresobioven#gmail.com";
var subject = "Constancia de inscripción - BIOVEN 2015";
var body = "Estimado " + full_name + ",<br/><br/> A través de este correo electrónico le hacemos entrega de su constancia de inscripción en el V Congreso Venezolano de Bioingeniería - BIOVEN 2015, la cual deberá presentar el primer día del congreso durante la verificación de registro.<br/><br/> Agradecidos,<br/><br/> <b>Comité Organizador del BIOVEN 2015</b>";
GmailApp.sendEmail(email_address, subject, body, {name: 'Congreso BIOVEN 2015', bcc: bcc_email, htmlBody: body, replyTo: reply_email, attachments: pdf});
//Guardando PDF en Drive
var folder_id = "Folder ID Here";
DriveApp.getFolderById(folder_id).createFile(pdf);
//Borrando archivo DOC temporal
DocsList.getFileById(copyID).setTrashed(true);
}

Try defining your variable payment_worth higher up in the code:
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
//Other var definitions
var payment_worth = 0;
Give it an initial value of zero. Presently, if your Case/Select ever fails, the variable payment_worth would be undefined.
Just an idea. Don't know if it's a good idea. ;)
Case Select would look like this:
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 150.00;
break
case "Profesional":
payment_worth = 200.00;
break
}

Related

Problem when printing data from an object array, it appears incorrectly

I have this program where there are a series of registered students and when they put their name, their data and the name of the teacher they have assigned.
When inserting a new student, the only thing that it does to me correctly is to print if the teacher exists or not, since the student's data does not show them to me, and finally I have a failure in the last line of the javascript code related to innerhtml , the error in question is:
Uncaught TypeError: Cannot set properties of null (setting
'innerHTML')
at mensaje.js:74
now the code:
html:
<button onclick="infoalumno()">Informacion del alumno</button>
<button onclick="insertar()">Introducir nuevo alumno</button>
<div id="info"></div>
and javascript code:
function alumno(nombre, edad, nota, profesor) {
this.nombre = nombre;
this.edad = edad;
this.nota = nota;
this.profesor = profesor;
}
function profesor(nombre, asginatura) {
this.nombre = nombre;
this.asginatura = asginatura;
}
var profesores = new Array(3);
profesores[0] = new profesor("Paco","Plastica");
profesores[1] = new profesor("Anton","Biologia");
profesores[2] = new profesor("Jacinto","Lengua");
var alumnos = new Array(2);
alumnos[0] = new alumno("Jose",24,7,profesores[0]);
alumnos[1] = new alumno("Jacobo",23,7,profesores[2]);
function infoalumno() {
var buscar = prompt("Inserta el nombre del alumno que quieres buscar");
var comprobar = false
for (let i = 0; i < alumnos.length; i++) {
if (buscar == alumnos[i].nombre) {
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor.nombre);
comprobar = true;
}
if (comprobar == false) {
document.write("Alumno " + buscar + "no existe");
}
}
}
function insertar() {
var comprobar2 = false;
var nombre = prompt("Insertar el nombre del alumno");
var edad = parseInt(prompt("Ingresa la edad"));
var nota = parseInt(prompt("Ingresa la nota"));
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor[i]);
alumnos.push(newalumno);
comprobar2=true;
break;//la sentencia break permite terminar de forma abrupta un bucle y la sentencia continue permite saltarse algunas repeticiones del bucle. ... La utilidad de break es terminar la ejecución del bucle cuando una variable toma un determinado valor o cuando se cumple alguna condición.
}
}
if(comprobar2==false){
document.write("Profesor "+profesor+" no existe");
}
}
var infoprofesor ="Profesores";
for (let i = 0; i < profesores.length; i++) {
infoprofesor = infoprofesor + profesores[i].nombre+"<br>";
}
document.getElementById("info").innerHTML = infoprofesor;
1)
The teacher does not appear his name instead appears [object Object]
In this code
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor);
This alumnos[i].profesor will be a Profesor object like from calling new Profesor(...). If you wanted to show the name it would look like alumnos[i].profesor.nombre
2)
And when inserting a new student, the only thing that it does to me
correctly is to print if the teacher exists or not.
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor);
alumnos.push(newalumno);
comprobar2=true;
break;
}
}
In this loop you have a related issue. The result from prompt will just be a string (your var profesor). However when you go to make your new alumno it expects a profesor object (with nombre/asignatura).
In this case you're probably want to do var newalumno = new alumno(nombre, edad, nota, profesores[i]);

Html and Javascript with google script function error

with Google Script i have created this html that send datas to a google sheet taking in input some data from the url (after /exec?P=tonno&Q=3&C=Cliente+1 he takes in input P,Q,C):
<!DOCTYPE html>
<html>
<head>
<title> Modulo di Ordine </title>
<script type="text/javascript">
function doGet(e){
//HtmlService.setTitle("This is MYTITLE");
var result = '<-- Riepilogo Ordine --> \n';
if (e.parameter == 'undefined') {
result += "ERRORE SCONOSCIUTO NELL'ACQUISTO! non verrà inviato l'ordine";
return ContentService.createTextOutput(result);
}
else {
var ID = '1sl0P4auOdX8i67kZ9LA8dGXm59I_fc_tSOaPaOpL1Ek'; // identificativo della cartella di foglio (Spreadsheet ID)
// var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var Cartella = SpreadsheetApp.openById(ID); // Cartella identificata da ID
var Foglio = Cartella.getSheets()[0]; // nella parentesi quadra il foglio ---> 0 = primo, 1 = secondo, ecc.
var Cella_R = Foglio.getRange(2,5); // riga 2, colonna 5 -> cella E2
var Inserite = Cella_R.getValue() + 1; // numero di righe inserite (letto dal foglio) incrementato di 1
Cella_R.setValue(Inserite); // scrive nel fogio il valore incrementato di «Inserite»
// var Riga = Foglio.getLastRow() + 1;
var Riga = Inserite + 2; // Riga in cui scrivere i dati
result += 'Codice Ordine: #' + Riga; // calcola la riga su cui scrivere i dati
var Cella_D = Foglio.getRange(Riga,1); // D = Data --------------> colonna 1
var Cella_O = Foglio.getRange(Riga,2); // O = Orario ------------> colonna 2
var Cella_T = Foglio.getRange(Riga,3); // T = Temperatura -------> colonna 3
var Cella_U = Foglio.getRange(Riga,4); // U = Umidità relativa --> colonna 4
var Cella_C = Foglio.getRange(Riga,5); // C = Cliente ----------->
var answer = "";
// SpreadsheetApp.setActiveSheet(sheet);
// var rowData = [];
var Giorno_Ora = new Date(); // legge data ed ora attuali
var Data = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'dd/MM/yyyy'); // estrae la data da Data_Ora
var Orario = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'HH.mm.ss' ); // estrae l'orario da Data_Ora
Cella_D.setValue(Data); //scrive la Data
Cella_O.setValue(Orario); //scrive l'orario
for (var parametro in e.parameter) {
var valore = Pulisci(e.parameter[parametro]); //estrae il valore del paramentro senza virgolette
switch (parametro) { // condizione case
case 'P':
Cella_T.setValue(valore); // Scrive il prodotto
result += '\nProdotto: ' + valore + ''; // Scrive messaggio risposta
break;
case 'C':
Cella_C.setValue(valore); // Scrive il cliente
result += '\nCliente: ' + valore + ''; // Scrive messaggio risposta
break;
case 'Q':
Cella_U.setValue(valore); // Scrive la quantità
result += '\nQuantità: ' + valore + ' pezzi'; // Scrive messaggio risposta
break;
default: //in caso di errore:
result += "\n\nParametri non validi!. L'ordine non verrà preso in considerazione";
}
} //se tutto va bene passa avanti con il successo
result += '\n\nEseguito con successo! Qualcuno provvederà a prendere in considerazione il suo ordine.';
}
return ContentService.createTextOutput(result); // Restituisce il Riepilogo dell'ordine
}
function Pulisci( value ) {
return value.replace(/^["']|['"]$/g, ""); // sostituisce cosa a cosa???
}
</script>
</head>
<body>
<p>Sicuro di voler procedere con l'ordine?</p> <br>
<input id="clickMe" type="button" value="clickme" onclick="doGet();" />
</body>
</html>
The problem is that when I press the button to call the function doGet(), this is the error and the function doesn't go on:
userCodeAppPanel:5 Uncaught TypeError: Cannot read property 'parameter' of undefined
at doGet (userCodeAppPanel:5)
at HTMLInputElement.onclick (userCodeAppPanel:1)
Can pls somebody help me?
ContentService, SpreadsheetApp, and even doGet(e) are server side functions they run on a Google Server not on your browser. You need to restructure your entire code and utilize some intermediate javascript functions and possibly google.script.run you would be well served to do a little more research in some of the examples provided here at SO.
The idea of using doGet(e) as a clientside function is rather ridculuous because the whole idea is that it's supposed to be an endpoint on the server. It's ridiculous to consider it as a clientside function.
To resolve the issue you are facing, you need to change your button HTML element to the below code -
<input id="clickMe" type="button" value="clickme" onclick="doGet(event);" />
Since you are using inline event handler, you need to pass the event as argument to onClick method. Please refer to this post in-case you have any queries.

pass an array in a function to string JavaScript

I have the following problem with the following code:
When I pass the Array to "track" I always get an error, I think it may be because an object is being passed and a String, but I'm not sure and I can't check it.
for (var i = 0; i < data.twKeyword.length; i++){
var stream = client.stream('statuses/filter', {track: data.twKeyword[i]});
}
I have tried:
data.twKeyword
data.twKeyword[i]
[data.twKeyword]
data.twKeyword
data.twKeyword[i]
'data.twKeyword[i]'
data.twKeyword[0].value
data.twKeywprd[0].toString()
And none of these options has given me a positive result.
He creado una variable nueva a la que le he ido pasando los valores del Array:
var x1 = JSON.stringify(data.twKeyword[i].name);
Después como estos valores se mostraban con doble comillas (""), he utilizado el siguiente código para eliminarlas:
x1.replace(/['"]+/g, '')
El código ha quedado así, y funciona:
for (var i = 0; i < data.twKeyword.length; i++){
var x1 = JSON.stringify(data.twKeyword[i].name);
var stream = client.stream('statuses/filter', {track: x1.replace(/['"]+/g, '')});
}

Parse a SRT file with jQuery Javascript

I'm trying to parse .srt but I get an internal error and I can't figure out what is it.
Here is my code:
var subtitles;
jQuery.get('SB_LKRG-eng.srt', function(data) {
//alert(data);
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
//alert(srt);
srt = strip(srt);
//alert(srt);
var srt_ = srt.split('\n\n');
alert(srt_);
var cont = 0;
for(s in srt_) {
st = srt_[s].split('\n');
alert(st);
if(st.length >=2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if(st.length > 2) {
for(j=3; j<st.length;j++)
t += '\n'+st[j];
}
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
//alert(subtitles[cont].start);
}
cont++;
}
});
I can extract the first 4 subtitles and then the code stops and breaks exception: TypeError, I can't understand why...
Here a sample of the subtitles file:
1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
Part of the code is from: http://v2v.cc/~j/jquery.srt/jquery.srt.js
Can anyone help me?
Thank you
var PF_SRT = function() {
//SRT format
var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
var _regExp;
var init = function() {
_regExp = new RegExp(pattern);
};
var parse = function(f) {
if (typeof(f) != "string")
throw "Sorry, Parser accept string only.";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n')
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
return result;
}
var toLineObj = function(group) {
return {
line: group[1],
startTime: group[2],
endTime: group[3],
text: group[4]
};
}
init();
return {
parse: parse
}
}();
 
jQuery.get('demo.srt')
.done(function(text) {
try {
//Array with {line, startTime, endTime, text}
var result = PF_SRT.parse(text);
} catch (e) {
//handle parsing error
}
});
Demo
https://jsfiddle.net/5v7wz4bq/
Here is one problem:
o = strip(st[1].split(' --> ')[1]);
At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2.
And here is another:
subtitles[cont].number = n;
....
Neither is the subtitles declared, nor its properties .number, ... etc.
Update
Here is a sample that works (switched the jQuery "read srt file" part for the data)
var data = document.getElementById("data").innerHTML;
data = data.replace(/>/g,">");
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
var subtitles = [];
for(s in srt_) {
st = srt_[s].split('\n');
if(st.length >=2) {
var st2 = st[1].split(' --> ');
var t = st[2];
if(st.length > 2) {
for(j=3; j < st.length;j++)
t += '\n'+st[j];
}
subtitles[cont] = { number : st[0],
start : st2[0],
end : st2[1],
text : t
}
console.log(subtitles[cont].number + ": " + subtitles[cont].text);
document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "<br>";
cont++;
}
}
<div id="data" style="display:none">1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
</div>
It is better to use the following regex to cover them if the number of lines of text in each section increases
/(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g
View the output on the console
let subtitle = document.getElementById('subtitle').value;
console.log(_subtitle(subtitle));
function _subtitle(text) {
let Subtitle = text;
let Pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g;
let _regExp = new RegExp(Pattern);
let result = [];
if (typeof (text) != "string") throw "Sorry, Parser accept string only.";
if (Subtitle === null) return Subtitle;
let Parse = Subtitle.replace(/\r\n|\r|\n/g, '\n');
let Matches;
while ((Matches = Pattern.exec(Parse)) != null) {
result.push({
Line: Matches[1],
Start: Matches[2],
End: Matches[3],
Text: Matches[4],
})
}
return result;
}
<textarea id="subtitle">1
00:00:00,000 --> 00:00:00,600
Hi my friends
2
00:00:00,610 --> 00:00:01,050
In the first line, everything works properly
But there is a problem in the second line that I could not solve :(
3
00:00:01,080 --> 00:00:03,080
But then everything is in order and good
4
00:00:03,280 --> 00:00:05,280
You do me a great favor by helping me. Thankful</textarea>

onChange event not working on IE9/10 when there are other events?

I'm facing this embarrassing situation. First, I'm on IE 10 right now, but this problem has been detected on IE9 as well. I have this input field and I need 2 events to work on it:
- onKeyUp, to check if the field's value is numeric; and
- onChange, to run some JS when the right number is inputted
If assigned separately, they work just fine. However, whenever I set these 2 events on the input field, the onChange event won't trigger, no matter what. All the other JS on this page has been stripped to prevent interference.
Below is the JS code for the onKeyUp:
<script>
function CampoNumerico(campo){
var valor = campo.value;
var novoValor = '';
var pontoPosicao = '';
if (isNaN(valor)){ // se nao for numero, devemos retornar o campo ao ultimo valor valido
alert(valor + " nao eh um numero valido");
novoValor = campo.defaultValue;
}
else{ //sendo um numero, buscamos a posicao de sua eventual virgula
valor = valor.split('');
for (var i = 0; i < valor.length; i++){
if (valor[i] == '.' && pontoPosicao == ''){
pontoPosicao = i;
}
}
// se nao houver ponto, o novo valor do campo sera igual ao valor de entrada da funcao
if ( pontoPosicao == ''){
for (var i = 0; i < valor.length; i++){
novoValor += valor[i];
}
}
else{ // se houver o ponto, registramos o novo valor igual ao valor de entrada, ate o limite de casas decimais
var tamanho = ((pontoPosicao + 3) < valor.length)? pontoPosicao + 3 : valor.length;
for (var i = 0; i < tamanho; i++){
novoValor += valor[i];
}
}
if (pontoPosicao != '' && pontoPosicao < (valor.length - 3)){ // se houver um ponto e mais de 2 casas decimais, alertamos o usario e desconsideramos as casas adicionais
alert("Aviso: " + campo.value + " tem mais de 2 casas decimais; serão consideradas apenas as primeiras casas - " + novoValor);
}
}
// terminamos por atualizar o valor do campo
campo.value = novoValor;
} // fim da CampoNumerico
</script>
Below is the field I'm trying to assign this script to:
<input type='text' name='campo' value='0' onchange='alert("1")' onkeyup='CampoNumerico(this)'>
At this point I just want to alert "1" when the onchange is triggered, but I'm unable to do even this simple action...
Interestingly, this coding works on other browsers just fine - Chrome & Firefox. Can anyone help me with this embarrassing situation? Thanks in advance for any thoughts.
EDIT - input field now visible separately

Categories

Resources