getting undefined value:app script - javascript

Here, i am trying to send a mail to replyEmail specified below. But it is giving as undefined value. Why its happening even though i am giving correct email id in google form? Some times its coming correct. But for another time its giving as undefined value.
function sendEmail(e) {
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1],
language = e.values[2],
meetingType = e.values[3],
eventDate = e.values[4],
clientName = e.values[5],
detailedDirections = e.values[6],
onSitePOCName = e.values[7],
onSitePOCNumber = e.values[8],
department = e.values[9],
contactPhoneNumber = e.values[10],
approval = e.values[11]; //the one we need to modif,
requestorEmail = e.values[12],
managerEmail = e.values[13],
Language2 = e.values[14],
interpreterName = e.values[15],
interpreterAgency = e.values[16],
dateConformationSent = e.values[17],
specialNotes = e.values[18];
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
// might be that the & needs to be a ?
var approve = url + '?approval=true' + '?reply=' + requestorEmail;
var reject = url + '?approval=false' + '?reply=' + requestorEmail;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
var html = [
"<html>",
"<body>",
"<h2>please review</h2> <br/>",
"<p>" + language +" " + serviceInformation,
"<p>" + meetingType + " on " + eventDate + " for " + clientName,
"<p>Location: " + department,
"<p>Requester: " + requestorEmail,
"<p>Approve<br/>",
"<p>Reject<br />",
"</body>",
"</html>";
].join('');
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {
htmlBody: html
});
}
function doGet(e) {
var app = UiApp.createApplication(),
aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule',
msg = "Your manager said :" + aprovalResponce;
var replyEmail = e.parameter.reply; // !!!
Logger.log(replyEmail);
MailApp.sendEmail(replyEmail, "Approval Request", msg);
var helloWorldLabel = app.createLabel(msg);
app.add(helloWorldLabel);
return app;
}

Its because space is not accepted while parsing the data in google script.It should be encoded and then the data is to be send.It can be encoded using encodeURIcomponent().

Related

How to implement pagination in Firebase using JavaScript?

I am working on Firebase pagination using JavaScript. I have implemented a soft delete feature where the record is not deleted in Firebase but deleted in the web display.
So when a soft delete is being done, the visible flag in Firebase becomes false. I want to display on my web form, the contacts whose visible flag is true using JavaScript ( with the NEXT and PREV buttons ).
Since I am new to this, I would love to get suggestions and help!!
A Snapshot of Firebase is as follows:
My code of getting first three records initially is as follows :
function getData() {
var total="";
var firstRef = firebase.database().ref("Persons/").orderByChild("visible").endAt("true").limitToFirst(3);
firstRef.on("value", function (data) {
console.log(data.val());
a = data.val();
var keys = Object.keys(a);
key1 = keys[0];
key2 = keys[1];
console.log("Key 1" + keys[0]);
for (var i = 0; i < keys.length; i++)
{
var k = keys[i];
var fname = a[k].fname;
var lname = a[k].lname;
var mno = a[k].mno;
var email = a[k].email;
var image = a[k].image;
var visible = a[k].visible;
if (visible == true) {
total += "<div><br/></div<div><b>KEY ID: </b><h1>" + k + "</h1></div><div><br/></div><div><img src=" + image + " alt=NoProfilePic class=imgsrc></div><div><b>FIRST NAME : </b>" + fname + "</div><div><b>LAST NAME : </b>" + lname + "</div><div><b>MOBILE NO : </b>" + mno + "</div><div><b>EMAIL : </b>" + email + "</div><div><br/><b><hr><hr></b></div>";
document.getElementById('total').innerHTML = total;
}
}
},
function (error) {
console.log("Error: " + error.code);
});
}
To get the Next three records (which will be called when the NEXT button is pressed ), I have written a code as follows :
function next() {
var total="";
var lastRef = firebase.database().ref("Persons").orderByKey().startAt(key2 + "a").limitToFirst(3);
lastRef.on("value", function (data) {
c = data.val();
var keys = Object.keys(c);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var visible = c[k].visible;
if(visible==true)
{
var fname = c[k].fname;
var lname = c[k].lname;
var mno = c[k].mno;
var email = c[k].email;
var image = c[k].image;
total += "<div><br/></div<div><b>KEY ID: </b><h1>" + k + "</h1></div><div><br/></div><div><img src=" + image + " alt=NoProfilePic class=imgsrc></div><div><b>FIRST NAME : </b>" + fname + "</div><div><b>LAST NAME : </b>" + lname + "</div><div><b>MOBILE NO : </b>" + mno + "</div><div><b>EMAIL : </b>" + email + "</div><div><br/><b><hr><hr></b></div>";
document.getElementById('total').innerHTML = total;
}
}
key3=key1;
key4=key2;
key2=keys[2];
key1=keys[0];
},
function (error) {
console.log("Error: " + error.code);
});
}
I am new to Firebase, so please do correct me if I am wrong and also, if anybody could help me with PREV, it would be great!!
Thanks!!

How do I hyperlink JSON API return values with variable URL addresses?

I have an HTML/CSS search bar where people can type a keyword and, on click, my Open States JSON API code returns New Jersey state bills that match that keyword.
Search Bar Screenshot
Screenshot of a Result
I want the bill titles that are returned to be hyperlinked to their page on the New Jersey state legislature site, but I can only find instructions for how to hyperlink a return with a static site.
Here is my JavaScript code so far (with API key removed):
e.preventDefault();
// console.log($("#billID").val());
var billSearchValue = $("#billID").val();
if(billSearchValue=='')
{
alert("Enter Desired Query Parameters");
} else{
// console.log(billSearchValue);
}
var searchQuery = "&q=" + billSearchValue;
var baseUrl = "http://openstates.org/api/v1/bills/?state=nj";
var apiKey = "";
var apiKeyParam = "&apikey=";
var apiKeyParams = apiKeyParam + apiKey;
var urlJSON = baseUrl + searchQuery + apiKeyParam + apiKey;
// console.log(urlJSON);
$.getJSON(urlJSON, function (data) {
var billsVar = [];
$.each(data, function(key, val) {
billsVar.push(val);
});
for (var i = 0; i < billsVar.length; i++) {
var billList = "<li>Bill <ul class=\"ul-sub\">"
var billTitle = "<li><strong>Bill Title</strong>: " + billsVar[i]['title'] + "</li>";
var billCreatedAt = "<li><strong>Bill Created</strong>: " + billsVar[i]['created_at'] + "</li>";
var billUpdatedAt = "<li><strong>Bill Updated</strong>: " + billsVar[i]['updated_at'] + "</li>";
var billID = "<li><strong>ID</strong>: " + billsVar[i]['id'] + "</li>";
var billChamber = "<li><strong>Bill Chamber</strong>: " + billsVar[i]['chamber'] + "</li>";
var billState = "<li><strong>Bill State (Probably Don't Want/Need This)</strong>: " + billsVar[i]['state'] + "</li>";
var billSession = "<li><strong>Bill Session</strong>: " + billsVar[i]['session'] + "</li>";
var billType = "<li><strong>Bill Type</strong>: " + billsVar[i]['type'] + "</li>";
var billSubjects = "<li><strong>Subjects</strong>: " + billsVar[i]['subjects'] + "</li>";
var billBillID = "<li><strong>Bill ID</strong>: " + billsVar[i]['bill_id'] + "</li>";
var billOutput = billList + billTitle + billCreatedAt + billUpdatedAt + billID + billChamber + billState + billSession + billType + billSubjects + billBillID + "</ul></li>";
$("#jsonlist").append(billOutput);
}
});
})
});
After a bit of research I see that a bill hyperlink is like this:
http://openstates.org/nj/bills/{Bill Session}/{Bill ID}/
I can't test my code because I have no API key, but the solution could be something like:
var billTitle = '<li><strong>Bill Title</strong>: '
+ '<a href="http://openstates.org/nj/bills/' +
billsVar[i]['session'] + '/' + billsVar[i]['bill_id'].split(' ').join('') + '/">'
+ billsVar[i]['title'] + '</a></li>';

How to return a value in the only non-blank column in a range for sendEmail function in Google App Scripts

The issue is: I can't find a way to return the value for 'Course' because each form submission generates a new row where the name of the course is spread over columns E to M (column 4 through 12).
In each row, there is only one 'Course' name in one of the columns from E to M (e.g only in F) and all other columns are blank. (Users can only select one course and all the other columns will be blank. I have to categorize the courses into the 9 columns because of the page breaks in order to split the sheer number of options that users select the course from.) How do I return the value of the only non blank cell from E to M which will be entered in the email ?
I was advised to insert the entire findCourse function inside of the sendEmail function before any of the other code. I did so but I have still been receiving failure notifications of the Google App Scripts: TypeError: Cannot read property "values" from undefined. (line 14, file "Code") (referring to var value = e.values[i])
The full code below:
function sendEmail(e) {
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
}
var Name = e.namedValues["Full name as appear in NRIC"];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
After rearranging findCourse as its own function: sorry if I made any mistakes here but i'll try my best to follow all suggestions. If i've added in Logger.log(e) correctly, both functions seem to be undefined
function sendEmail(e) {
Logger.log(e);
var Name = e.values[2];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
var courseToTake = findCourse(e);
Logger.log(e);
}
I will really deeply appreciate any help or alternative solutions here.
Thank you!
What I changed in your code to address your question:
I assigned the onFormSubmit trigger to your sendEmail function so the event object would no longer be undefined
I added a call to findCourse() so your course variable would no longer be undefined
I fixed the undefined check by changing if(value != undefined) to if(typeof value !== 'undefined')
I added a check for a blank value (This was the important bit in the logic after the faulty undefined check) if(value != '')
Explanation:
To trigger the event, an installable trigger needs to be setup for the On Form Submit event that points to your sendEmail function. This can be found in Resources -> Current Project Triggers
To retrieve the course, you need to call your function findCourse() and pass in the e event object. Example: var course = findCourse(e);. This will assign the return value from findCourse(e); to the course variable. You can then use this variable like normal within the rest of your statements.
When checking for undefined, you need to use typeof and then check for the string of 'undefined', or your check will ironically throw an undefined exception.
The values of the form submit should not be undefined, blank values should just be blank strings. so checking for non-blank strings was necessary to get the course name from the values array.
Fixed Code:
function sendEmail(e) {
Logger.log(e)
var course = findCourse(e);
var Name = e.values[19];
var Start = e.values[12];
var End = e.values[14];
var StartTime = e.values[13];
var EndTime = e.values[15];
var Details = e.values[11];
var Cost = e.values[17];
var Email = e.values[20];
var ROname = e.values[21];
var ROemail = e.values[22];
var Location = e.values[16];
var subject = "Training Approval Request for " + course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email+";" + "redactedEmail", subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 2; i <=10; i ++){
//pull value into variable
var value = e.values[i];
if (typeof value !== 'undefined'){ //If value is defined
if(value != ''){ //If value is not blank
//if we find an actual non-blank string value, set the course to take variable
courseToTake = value;
}
}
}
return courseToTake;
}

How do I call the PHP mail() function in my JS?

I have a dilema. I've created this order request page for a website I'm building, and here's how it works:
You check/uncheck core items, and based on it's state (active or unactive), it'll apply a true/false value to a boolean in the coresponding order.js. Likewise, it'll take desired unit count for other items, and your information, and apply them to variables.
It groups those variables into arrays and, right now, console.log() them.
Here's where the trouble comes...this is a snippet of the order.js file.
function compileInfo() {
console.log("compileInfo active");
var name = "Name: " + $("#name").val() + "\n";
var email = "Email: " + $("#email").val() + "\n";
var phone = "Phone: " + $("#phone").val() + "\n";
var weddingDate = "Wedding Date: " + $("#date").val() + "\n";
var comments = "Comments: " + $("#comments").val() + "\n";
var base = "Base Experience: " + $("#base").hasClass("active") + "\n";
var special = "Special Edition: " + $("#special").hasClass("active") + "\n";
var teaser = "Teaser Trailer: " + $("#teaser").hasClass("active") + "\n";
var raw = "Raw Footage: " + $("#raw").hasClass("active") + "\n";
var standard = "Standard Shipping: " + $("#standard").hasClass("active") + "\n";
var expedited = "Expedited Shipping: " + $("#expedited").hasClass("active") + "\n";
var dvd = "Standard DVD: " + a + "\n";
var br = "Standard Blu-Ray: " + b + "\n";
var dvdSe = "Special DVD: " + x + "\n";
var brSe = "Special Blu-Ray: " + y + "\n";
var info = new Array();
info[0] = name;
info[1] = email;
info[2] = phone;
info[3] = weddingDate;
info[4] = comments;
var services = new Array();
services[0] = base;
services[1] = special;
services[2] = teaser;
services[3] = raw;
var delivery = new Array();
delivery[0] = standard;
delivery[1] = expedited;
var extras = new Array();
extras[0] = dvd;
extras[1] = br;
extras[2] = dvdSe;
extras[3] = brSe;
var dataVar = info + "\n" + services + "\n" + delivery + "\n" + extras;
var dataVarJSON = JSON.stringify(dataVar);
console.log(dataVar);
$.ajax({
type: "POST",
url: "order.php",
data: {data : dataVarJSON},
success: function() {
console.log("SUCCESS");
}
});
}
function validate() {
var name = $("#name").val();
var email = $("#email").val();
var weddingDate = $("#date").val();
if (name === "" || email == "" || weddingDate == "") {
alert("You must complete all required fields to send this request.");
} else {
console.log("working");
compileInfo();
return true;
}
}
Here's my recieving PHP:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$body = json_decode(stripslashes($_POST['data']));
$to = "thekevinhaube#gmail.com";
$subject = "Order Request";
function sendInfo() {
mail($to, $subject, $body);
}
?>
Now, I'm far from a PHP expert. This is my first encounter with it, in fact. How can I get it to send. It seems to POST just fine, but isn't sending to the email adress listed. Any and all help is appreciated! Again, this is my first time with PHP, so...
You need to give sendInfo some parameters:
function sendInfo($to, $subject, $body) {
...
}
And don't try mail() on your localhost, try it - if possible - online.

How update data by Javascript

How can I, on the OnChange event, update data in my database ?
I have a WebMethod, that returns a HTML, so I can't see those elements, so I think he solution will be a javascript function.
A textarea catch the text from the database, if the user alter this, the database field has to be updated.
[WebMethod]
public static object ListAdvertise(string transaction)
{
StringBuilder retorno = new StringBuilder(160000);
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
string Credenciada = tk2.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value);
string select3 = "SELECT * FROM San_Imovel WHERE Status_Id = 1 AND Credenciada_Id = " + Credenciada + " AND Transacao_Id IN (" + transacao + ") ORDER BY NomeCidade, NomeBairro, Imovel_Id ASC";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
Imovel_Id = r3["Imovel_Id"].ToString();
Endereco = r3["Descricao"].ToString() + " " + r3["Logradouro"].ToString() + " " + r3["Numero"].ToString() + "/" + r3["DscComplemento"].ToString() + " " + r3["Complemento"].ToString() + " - " + r3["NomeBairro"].ToString();
TextoAnuncio = r3["TextoAnuncio"].ToString();
if (count % 2 == 0)
{
classe = "EstiloDalinhaGrid";
}
else
{
classe = "EstiloDalinhaAlternativaGrid";
}
retorno.Append("<tr class='" + classe + "'>");
retorno.Append("<td>");
retorno.Append(Imovel_Id);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append(Endereco);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<textarea id='txtArea'>");
retorno.Append(TextoAnuncio);
retorno.Append("</textarea>");
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<input type='checkbox' class='imoveisMarcados' id='" + Imovel_Id + "' />");
retorno.Append("</td>");
retorno.Append("</tr>");
count++;
}
retorno.Append("</table>");
con3.Close();
return new
{
retorno = string.Format(retorno.ToString())
};
i think you have to use Ajax for you to be able to update your data base .
check this link to learn more about ajax with Php (you chose whatever server side langage you'd like)
Ajax with PHP

Categories