Google Apps Script for Form, Generate Unique ID Number - javascript

I created a simple Google form with the fields:
Name, E-mail, Salary and Request.
When the user completes the form, I want to send him/her an e-mail with the info. However, I want to use the "Request" field to plug in a unique number that the user can refer to if they need further correspondence. If the user enters anything in the 'Request' field, I want to discard it and use the number that I generate (both in the response and in the spreadsheet).
I've been able to piece together the script using other info I've found. It seems to work for everything except the e-mail response going back to the user.- It does not contain the number that I want to use in the 'Request' field, but instead sends back any input that the user puts in the 'Request' field. The spreadsheet looks ok (it has my number in the 'Request' field.)
Here's my script:
function sendFormByEmail(e) {
var capsht = SpreadsheetApp.getActiveSheet();
var caprow = SpreadsheetApp.getActiveSheet().getLastRow();
capsht.getRange(caprow,5).setValue("Cap-"+caprow);
var admin = "admin#xxx.com";
try {
var recipient = e.namedValues["Email"];
var subject = "Capacity Request Form Received";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for (var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
MailApp.sendEmail(recipient, subject, message);
}
catch (error) {
MailApp.sendEmail(admin, "Error with form submission response email", error.message);
}
}

try it like this :
(added comment in code and deleted repetitions)
function sendFormByEmail(e)
{
var capsht = SpreadsheetApp.getActiveSheet();
var caprow = capsht.getLastRow();
var codenumber = "Cap-"+caprow
capsht.getRange(caprow,5).setValue(codenumber);
var admin = "admin#xxx.com";
try {
var recipient = e.namedValues["Email"];
var subject = "Capacity Request Form Received";
var headers = capsht.getRange(1,1,1,capsht.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
if(i!=4){
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
}else{ // if i==4 (column nr5)then use your code number
message += headers[i] + ' = '+ codenumber + "\n\n";
}
MailApp.sendEmail(recipient, subject, message);
}
catch (error)
{
MailApp.sendEmail(admin, "Error with form submission response email", error.message);
}
}

Related

How to pass long data to mySql database at freemysqlhosting.net

I am using freemysqlhosting.net to host my database and I am doing actions by using their library :
var MySql = {
_internalCallback : function() { console.log("Callback not set")},
Execute: function ( Sql, Callback)
{
MySql._internalCallback = Callback;
Host = "sql9.freemysqlhosting.net";
Username = "myUserName";
Password = "MyPassword";
Database = "MyDatabase";
var strSrc = "http://mysqljs.com/sql.aspx?";
strSrc += "Host=" + Host;
strSrc += "&Username=" + Username;
strSrc += "&Password=" + Password;
strSrc += "&Database=" + Database;
strSrc += "&sql=" + Sql;
strSrc += "&Callback=MySql._internalCallback";
alert(strSrc);
console.log('rabee: '+ strSrc);
var sqlScript = document.createElement('script');
sqlScript.setAttribute('src', strSrc);
document.head.appendChild(sqlScript);
}
};
Then if I want to insert data into table inside this database, I do it simply by doing this:
var command =
"INSERT INTO myTable(id,name,email,data) VALUES ('2','rabee','test#test.com','anydata')";
MySql.Execute(command,function(data){
showAllRaws();
alert(JSON.stringify(data,null,2));
});
When I insert short data inside the data column I got a successful callback, but when I insert long data nothing happens and no callback.
My questions are :
1- Is there any limitation for long URL request or am I doing something wrong?
2- How to replace their tiny library with AJAX request?
Please check your datatype in the database and whether you are using use "text" datatype it will accept all data.

javascript loop through array display detail - loop through a second array display details of 2nd url

I'm looking to build an app that searches for a person by name - I have achieved this part - and displays the person name. The second part of the app should also present more details for each person on click (this information should be retrieved from a second URL. Lastly the app should also inject an image when I click on that person. I haven't been able to make this work.
Can you guy help fix this or shine a light?
I have commented out what I have been trying to do.
https://codepen.io/edmonteiro/pen/qKeMLj
document.getElementById("subBtn").onclick = function(event){
//prevent default submission
event.preventDefault();
//grab the typed value in the text box
var name = document.getElementsByClassName("name")[0].value;
//Alternatively give an "id" attribute to the text box in the HTML
//for example, <input type="text" name="textboxname" class="name">, use:
//var name = document.getElementById("textboxname").value();
let ourRequest = new XMLHttpRequest();
//pass this search value as a parameter in URL to get results from database
ourRequest.open('GET', 'https://izrite.com:5555/leads?page=1&name=' + name, true);
//function to call when the AJAX request is completed
ourRequest.onload = function(){
//if request completed successfully
if(ourRequest.status === 200){
let ourData = JSON.parse(ourRequest.responseText);
let list = document.getElementById("list");
//process only if request returned a valid JSON data
if(typeof ourData === 'object'){
//if there are 1 or more results found
if(ourData.length > 0){
list.innerHTML = "<p><b>Matched names from database:</b></p>";
//for each `lead` in the array, print its name
for(lead of ourData){
list.innerHTML += "<p>Name: " + lead.name + "</p>";
/*-----------------------------------------------------------------*/
/* Second and third part of the test - to be continued. Not finished before the 5hours time frame mentioned on the challenge specs*/
// if((lead.id).value()==="0009bd06-a9ce-470e-b13a-acd2aaaa42d4"){
// let ourRequest2 = new XMLHttpRequest();
// ourRequest2.open('GET', 'https://izrite.com:5555/lead/0009bd06-a9ce-470e-b13a-acd2aaaa42d4', true);
// let moreDetails = document.getElementById('moreDetails');
// let ourData2 = JSON.parse(ourRequest2.responseText);
// if(typeof ourData2 === 'object'){
// //if there are 1 or more results found
// if(ourData2.length > 0){
// moreDetails.innerHTML = "<p><b>More details</b></p>";
// //for each `lead` in the array, print its name
// for(detl of ourData2){
// moreDetails.innerHtml += "<p>Name: " + detl.name + "</p><br><p>Make: " + detl.make + "</p><br><p>Model: " + detl.model + "</p><br><p>Derivative: " + detl.derivative + "</p>";
// // var myImage = new Image(100, 200);
// // myImage.src = 'https://izrite.com:5555/image/71890';
// // document.body.appendChild(myImage);
// }
// }
// }
// }
// ourRequest2.send();
/*-----------------------------------------------------------------*/
};
}else{
//no results found for this search query
list.innerHTML = "<p><b>No match found in database!</b></p>";
}
}else{
//response not in JSON format
list.innerHTML = "<p><b>Response is not in valid JSON format!</b></p>";
}
}
}
//send the AJAX request
ourRequest.send();
}
As far as I can understand your question, you want to type in the search box, hit "Search" and get the matched results from your database via AJAX.
Here is the JavaScript that works: (Remove your javascript in your CodePen and paste this to see it working.)
document.getElementById("subBtn").onclick = function(event)
{
//prevent default submission
event.preventDefault();
//grab the typed value in the text box
//getElementsByClassName is used because in your HTML, the text box has no "id" attribute
var name = document.getElementsByClassName("name")[0].value;
//if you give an "id" attribute to the text box in your HTML
//for example, <input type="text" name="textboxname" class="name">, use:
//var name = document.getElementById("textboxname").value();
let ourRequest = new XMLHttpRequest();
//pass this search value as a parameter in URL to get results from database
ourRequest.open('GET', 'https://izrite.com:5555/leads?page=1&name=' + name, true);
//function to call when the AJAX request is completed
ourRequest.onload = function()
{
//if request completed successfully
if(ourRequest.status === 200)
{
let ourData = JSON.parse(ourRequest.responseText);
var list = document.getElementById("list");
//process only if request returned a valid JSON data
if(typeof ourData === 'object')
{
//if there are 1 or more results found
if(ourData.length > 0)
{
list.innerHTML = "<p><b>Matched names from database:</b></p>";
//for each `lead` in the array, print its name and id
for(lead of ourData)
{
list.innerHTML += "<p>Name: " + lead.name + "<br />Id: " + lead.id + "</p>";
}
}
else
{
//no results found for this search query
list.innerHTML = "<p><b>No match found in database!</b></p>";
}
}
else
{
//response not in JSON format
list.innerHTML = "<p><b>Response is not in valid JSON format!</b></p>";
}
}
}
//send the AJAX request
ourRequest.send();
}
The forEach callback takes the current value as the first parameter and index as the second. Try:
ourData.forEach((element, index) => {
document.getElementById("app").innerHTML = `<p>${element.name}</p>`;
});
Try this
ourData.forEach((element, index) => {
document.getElementById("app").innerHTML += <p>${element.name}</p>;
});
innerHTML +=
Add to the HTML on each cycle.

How to set cookie using JavaScript after fetching API request in GCM Service Worker?

I have successfully implemented GCM and ServiceWorkers to receive push-notification.
My problem
Whenever there is a SOS update, I am sending a HTTP request to gcm-http which then shows up a normal notification on Google Chrome but without any payload or data.
According to Google Developers Doc, chrome cannot receive payload/data, so one have to manually fetch the notification from the backend when push event is triggered.
So to fetch the data I am requesting an url on my backend (in django) to send me the notification data. But problem lies here how will I know which notification's data I have to send from my database/model?
Note:- I am not maintaining a different database table/model to determine notifications read by the client, since its an SOS update and read/unread is not required.
Workaround which is not working:-
I can set a cookie on client's browser and on backend can get next notification (below is the code)
class GetSOSNotification(View):
notif_id = 0
def get(self, request):
if 'last_notif_id' in request.COOKIES:
notif_id = request.COOKIES.get('last_notif_id') + 1
sos = SOSUpdate.objects.get(id=notif_id)
else:
sos = SOSUpdate.objects.order_by('-timestamp').filter()[0]
notif_id = sos.id
data = dict()
data['notification'] = dict()
if sos.get_condition_display() and sos.get_subject_display():
data['notification']['title'] = sos.polling_station.name + " " + sos.get_subject_display() + " " + sos.get_condition_display()
elif sos.get_condition_display():
data['notification']['title'] = sos.polling_station.name + " " + sos.get_condition_display()
elif sos.get_subject_display():
data['notification']['title'] = sos.polling_station.name + " " + sos.get_subject_display()
else:
data['notification']['title'] = sos.polling_station.name + " SOS Alert!"
if sos.message:
data['notification']['message'] = sos.message
else:
data['notification']['message'] = "Please click here to check the details."
data['notification']['notif_id'] = notif_id
return JsonResponse(data)
but, I have to return JSON response, and therefoe I can't set cookie from server-side, therefore I planned to use data['notification']['notif_id'] on client-side (i.e., Javascript) to set cookie.
My SW.js's snippet looks like :
self.addEventListener('push', function(event) {
console.log('Push message', event);
event.waitUntil(
fetch("//localhost/get_sos_notification/").then(function(response){
if(response.status!=200){
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
return response.json().then(function(data){
if(data.error || !data.notification){
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = '//localhost/static/main/images/push-notification.png';
var notificationTag = data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
}).catch(function(err){
console.log('Unable to retrieve data', err);
var title = 'SOS - Update';
var message = 'We were unable to get the information, please click here to know the real message.';
var icon = '//localhost/static/main/images/push-notification.png';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
})
);
});
But I am not able to do document.cookie = last_notif_id=data.notification.notif_id at the place where I am handling received notification data (if successfully received), because the JS script is giving error Unable to retrieve data ReferenceError: document is not defined at http://localhost/static/main/js/sw.js
Additional information: //localhost/get_sos_notification/ is a GET request, returns JSON, and is mapped to class GetSOSNotification(View)
I have googled and searched SO a lot, but haven't got any solution.
Thanks in advance.

Printer.js not printing to console

So for some reason all of a sudden after I move my print functions to their own file and try to run the node command on my app.js file then it doesn't want to print anything in my console. Why is that?
I am still struggling with debugging this one as nothing is printing out when I run the following command.
node app.js myusernamehere
Anyone have any idea?
app.js
var profile = require("./profile.js");
var users = process.argv.slice(2);
users.forEach(profile.get);
profile.js
//Problem: We need a simple way to look at a user's badge count and Javascript points
//Solution: Use Node.js to connect to Treehouse's API to get profile information to print out
var https = require("https");
var http = require("http");
var printer = require("./printer.js");
function get(username) {
//Connect to API URL (http://teamtreehouse.com/username.json)
var request = https.get("https://teamtreehouse.com/" + username + ".json", function(response) {
var body = "";
//Read the data
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if (response.statusCode == 200) {
try {
//Parse the data
var profile = JSON.parse(body);
//Print the data
printer.printMessage(username, profile.badges.length, profile.points.JavaScript);
} catch(error) {
//Parse Error
printer.printError(error);
}
} else {
//Status Code Error
printer.printError({message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"});
}
});
});
//Connection Error
request.on('error', printer.printError);
}
module.exports.get = get;
printer.js
//Print out message
function printMessage(username, badgeCount, points) {
var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in Javascript";
console.log(message);
}
//Print out error messages
function printError(error) {
console.error(error.message);
}
module.exports.printMessage = printMessage;
module.exports.printError = printError;
I don't know what actually happened but it works now and nothing in my code was changed.

Uncaught Error: Can't form encode an Object

I am trying to call some Parse CloudCode that I wrote for Mailgun, but when I call it from my iOS app this is what I get:
E2015-09-16T05:52:37.410Z]v4 after_save triggered for EmailConfirmations for user HjHSYVX56t:
Input: {"object":{"createdAt":"2015-09-
16T05:52:37.399Z","email1":"test#trever.me","email2":"test#trever.me","name1":"Test Test","name2":"Test Test","objectId":"KPLpKdZqSO","updatedAt":"2015-09-16T05:52:37.399Z"}}
Result: Uncaught Error: Can't form encode an Object
I get this from the Parse Console, does anyone know what that means exactly?
Thank you!
Here is my CloudCode:
// bring in Mailgun
var Mailgun = require('mailgun');
// init Mailgun
Mailgun.initialize('sandboxcf52f1abbe6f4bbe80c055aecc31f58f.mailgun.org', 'key-b29acfb8411921998764456e247c30fa');
Parse.Cloud.afterSave("EmailConfirmations", function(request) {
// This function runs on INSERT and DELETE operations.
// Check to ensure account is new.
if (!request.object.existed()) {
var email1 = request.object.get("email1");
var email2 = request.object.get("email2");
var name1 = request.object.get("name1");
var name2 = request.object.get("name2");
var tradeDateTime = request.object.get("tradeDateTime");
var body = "Hello " + name1 + "&" + name2 + ",\n\n Your trade on" + tradeDateTime +
"has been approved, and will need to be processed in Empower, or via an Expresso ticket. " +
"Please process as soon as possible to ensure a successful trade.";
var sender = "test#test.com";
var subject = "Trade Confirmation";
}
Mailgun.sendEmail(
{
to: [email1, email2],
from: sender,
subject: subject,
text: body
}, onMailComplete, onMailError);
function onMailComplete (httpResponse) {
console.log(httpResponse);
console.log("Email sent to " + email1 + "and" + email2);
}
function onMailError (httpResponse) {
console.error(httpResponse);
console.error("Uh oh, something went wrong");
}
} /* eo func def */
);
And this is the code where I'm calling the cloud function:
PFCloud.callFunctionInBackground("EmailConfirmations", withParameters: ["objectId": objectID, "email1" : emailCurrentUser, "email2" : emailCurrentUser, "name1" : fullnameCurrentUser, "name2" : fullnameCurrentUser])
I guess you tried to send an HTTP request passing object as parameter where it expected string. Use JSON.stringify(object) before passing it.
For more info see: https://parse.com/questions/result-uncaught-error-cant-form-encode-an-object
EDIT:
Now i totally.. don't understand what's going on. You should re-read the Parse Cloud guide because you are mixing afterSave hooks with cloud function calls and those are different things.
I guess your cloud code should look like this:
// bring in Mailgun
var Mailgun = require('mailgun');
// init Mailgun
Mailgun.initialize('sandboxcf52f1abbe6f4bbe80c055aecc31f58f.mailgun.org', 'key-b29acfb8411921998764456e247c30fa');
Parse.Cloud.define("EmailConfirmations", function(request) {
var email1 = request.params.email1;
var email2 = request.params.email2;
var name1 = request.params.name1;
var name2 = request.params.name2;
var tradeDateTime = request.params.tradeDateTime;
var body = "Hello " + name1 + "&" + name2 + ",\n\n Your trade on" + tradeDateTime +
"has been approved, and will need to be processed in Empower, or via an Expresso ticket. " +
"Please process as soon as possible to ensure a successful trade.";
var sender = "test#test.com";
var subject = "Trade Confirmation";
Mailgun.sendEmail({
to: [email1, email2],
from: sender,
subject: subject,
text: body
}, onMailComplete, onMailError);
function onMailComplete (httpResponse) {
console.log(httpResponse);
console.log("Email sent to " + email1 + "and" + email2);
}
function onMailError (httpResponse) {
console.error(httpResponse);
console.error("Uh oh, something went wrong");
}
} /* eo func def */
);
And in the swift function call you can skip the objectID but you should add tradeDateTime of type NSDate

Categories