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

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.

Related

How to display MediumBLOB from MySQL database using Javascript

So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>
try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);

getting undefined value:app script

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().

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;
}

Javascript newline not working when sending to outlook

I have this little problem.
I have this javascript in my html page:
function myfunction(form)
{
var name = document.details.txtName.value + "\n";
var street = document.details.txtStreet.value + "\n";
var city = document.details.txtCity.value + "\n";
var stateProvince = document.details.txtStateProvince.value + "\n";
var postalCode = document.details.txtPostalCode.value + "\n";
var country = document.details.txtCountry.value + "\n";
var homeTel = document.details.txtHomeTel.value + "\n";
var workTel = document.details.txtWorkTel.value + "\n";
var fax = document.details.txtFax.value + "\n";
var mobile = document.details.txtMobile.value + "\n";
var email = document.details.txtEmail.value + "\n";
var enquiry = document.details.txtEnquiry.value + "\n";
var message = (name +
street +
city +
stateProvince +
postalCode +
country +
homeTel +
workTel +
fax +
mobile +
email +
enquiry);
alert(message);
location='mailto:somecrazyassemail#gmail.com?subject=Message From Redec Website&body=' + message;
return false; //So that the page can stay at its current location.
In the messagebox that pops up, it displays the strings underneath each other, which I want.
but when this opens outlook it is all in one long string. how can I fix this?
}
The mailto is particular attribute. You have to encode the string using escape function.
But for the new lines, you can use %0D%0A.
See this site for more informations.
You're inserting the text as HTML, so new line characters '\n' are simply parsed as 'n'. To insert a line break, using the corresponding HTML element <br>.
For example:
var name = document.details.txtName.value + "<br>";
// ^^^^

Firefox thinks <fieldset> is a form element; Chrome doesn't

In my JavaScript program, I get values from a form through its elements and then print them in order, in an alert. This works fine in Firefox, but in Chrome the order is wacky and it ends with the "Submit" button.
I tried getting rid of the fieldset and adjusting the numbers, and it worked, but I liked the fieldset! Also, I can't just make an array and iterate through it because the fields are tab-order adjusted and I want to print them accordingly. Any suggestions?
Upon trying to validate I found that I do indeed need the fieldset for XHTML Strict. I've been storing the elements in an array, like so:
var $ = function (id) { return document.getElementById(id); }
function check() {
var x = $("myForm");
var user = new Array();
user[0] = x.elements[0].value;
user[1] = x.elements[2].value;
user[2] = x.elements[4].value;
user[3] = x.elements[1].value;
user[4] = x.elements[3].value;
user[5] = x.elements[5].value;
And then checking them using another couple of arrays and displaying the results in a pop-up:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
if (user[i] == "") {
display[i] = "You entered nothing.";
}
else if (user[i] == answers[i]) {
display[i] = "Correct!";
}
else {
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
}
WebKit bug (https://bugs.webkit.org/show_bug.cgi?id=48193).
I think you'll be better off using IDs:
<form ...>
<input ... id="q0" />
<input ... id="q1" />
<input ... id="q2" />
</form>
So you can write this JavaScript code:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display[i] = "You entered nothing.";
else if (user == answers[i])
display[i] = "Correct!";
else
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
Your code can receive a lot of improvement, too:
var answers = [ "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" ];
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display.push( "You entered nothing." );
else if (user == answers[i])
display.push( "Correct!" );
else
display.push ( "Wrong. The correct answer is \"" + answers[i] + "\"." );
}
alert(display.join('\n'));

Categories