Receive Files in Drive and send Confirmation Email - email

I would like to create a form that allows anyone to upload multiple files to my drop box. But I would also like for the person that uploads the file to receive a confirmation email. The following code uploads the files but does send the email. Please help!
Here is the .gs
function doGet(e) {return HtmlService.createHtmlOutputFromFile('form.html');}
function sendEmails(form) {
var message= ", your abstract was submitted. Send other work by APR 20";
var subject = "Application Received";
MailApp.sendEmail(form.myEmail, subject, message);
}
function uploadFiles(form) {
try {
var dropbox = "New Abstracts";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile1;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
var blob = form.myFile2;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
And here is the .html portion
<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="email" name="myEmail" placeholder ="Your email..">
<input type="file" name="myFile1" >
<input type="file" name="myFile2" >
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
return false;">
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
I trying this based on the codes found at:
http://www.labnol.org/internet/receive-files-in-google-drive/19697/

You can't append multiple calls to the script like this:
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
Only uploadFiles (the first one being called) gets executed. Everything after that is getting ignored.
You can add the code inside sendEmails() to the uploadFiles() as one solution? Or add it to the success handler? Or have uploadFiles() call sendEmails() once it is done...

Related

Contact Form 7 Redirecting Page based on Button Clicked

HTML
<input name="Pay_Now" id = "submit" type="submit" value="PayNow" />
<input name="Pay_at_Venue" id = "submit" type="submit" value="PayatVenue" />
Script
The Script i am placing in theme editor under Footer.php
document.addEventListener( 'wpcf7mailsent', function( event ) {
var lpLocation = document.getElementById("submit").name;
if (lpLocation == "Pay_Now") {
location = 'https://rzp.io/l/fgpayment/';
} else if (lpLocation == "Pay_at_Venue") {
location = 'https://www.fingurukul.org/thank-you/';
} else {
// do nothing
}
}, false );
</script>
I am unable to find the mistake. What am i doing wrong>
Both the button are redirecting to same page
Please Help with your expertise
Thanks in advance

File upload inside window.addEventListener

My brain's hurting. After my page loads, I get some HTML. This is a stripped-down version:
window.addEventListener('load', () => {
if (window.location.pathname === '/profile' && Cookies.get('token')) {
axios.get('/api/profile-info').then(res => {
const member = res.data.member
const memberInfo = `
<form enctype="multipart/form-data" id="uploadProfilePictureForm">
<input type="file"/>
<button onclick="uploadPicture(event)">Upload</button>
</form>
`;
})
}
})
I then handle the onclick event:
const uploadPicture = (event) => {
event.preventDefault()
const form = document.getElementById('uploadProfilePictureForm')
console.log(form) // Just shows the HTML form
}
This handler is placed before window.addEventListener
The file name appears on the page, but after clicking "Upload", it won't show in the console (which I plan to send to my server).
How do I allow an onclick event to handle a file upload?
Solved
Inside window.addEventListener(), I used a simple input tag:
<input type="file" id="fileUpload" onchange="uploadPicture()"/>
Then, outside this event listener, I defined the uploadPicture() function:
function uploadPicture() {
var FD = new FormData()
var fileInput = document.getElementById('fileUpload')
FD.append("pictureFile", fileInput.files[0])
const data = FD.entries().next().value
console.log('data\n', data) // This is the FormData array
}

upload a file using angular, express and mongodb's gridfs

I am new to these technologies and hence have limited knowledge on how to upload a file. During my research, I have seen ngUpload and other javascript/directive based solutions. However, I am trying the following and not sure what else I am missing to complete it.
I am trying to upload file after creating a blog using angular-express-blog application. I have the following code
In view.jade
fieldset
h5 Add Media
form(name='theForm', enctype="multipart/form-data")
.clearfix
label Document Name
.input: input(ng-model='form.docName', name='docName', type='text')
.clearfix
label File
.input: input(ng-model='form.file', type="file", name="file")
.actions
button(ng-click="uploadFiles('/page3files')") Upload Files
the controller, I do need to return to the uploadfile page hence, I am passing in /page3files.
$scope.uploadFiles = function( path ) {
//alert("upload files clikced");
$http.post('/api/uploadFile', $scope.form).
success(function(data) {
$scope.form.docName='';
$scope.form.file='';
$location.path(path);
});
};
In the express routes file
exports.uploadFile = function (req, res) {
console.log("doc name: " + req.body.docName);
console.log("file name: " + req.body.file.name);
console.log("file path: " + req.body.file.path);
res.json(true);
};
Unfortunately, I am getting an exception at req.body.file.name saying cannot read property 'name' of undefined.
Any assistance is much appreciated.
Thanks,
Melroy
for the $http.post() to be able to upload files you need to set some configurations.
headers : {'Content-Type': undefined},
transformRequest: angular.identity
You can use the simple/lightweight angular-file-upload directive that takes care of that for you.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim.
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
There are more info on the README page and there is a Demo page
You can send file data with FormData object. For Example:
HTML:
<fieldset>
<legend>Upload Video</legend>
<input type="file" name="photo" id="photo">
<input type="button" ng-click="uploadVideo()" value="Upload">
</fieldset>
JS:
$scope.uploadVideo = function () {
var photo = document.getElementById("photo");
var file = photo.files[0];
var fd = new FormData(); //Create FormData object
fd.append('file', file);
$http.post('/uploadVideo', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
// Do your work
});
};

Auto complete with multiple keywords

I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>

Editing and deleting a newly added table row using Jquery

I'm adding new rows dynamically to the existing table, the first column of the table holds the Edit & Delete buttons. I'm facing 2 problems with this:
Not able to Edit and Delete newly added rows, tried .live but couldn't make it work
Not able to get the record id of the newly added rows (ajax returns the record when new rows are added).
Code looks like this:
Adding new rows:
<script type="text/javascript">
$(function() {
$('#btnSubmit').click(function() {
var oEmployee = new Object();
oEmployee.Title = $("#Title").val();
oEmployee.Middlename = $("#MiddleName").val();
oEmployee.Lastname = $("#LastName").val();
oEmployee.Email = $("#Email").val();
var DTO = {'employee': oEmployee};
var options = {
type: "POST",
url: "WebService.asmx/InsertEmployee",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != "") {
if (parseInt(response.d) >= 1) {
var contactID;
contactID = parseInt(response.d);
$('#tblEmployee tbody tr:first').after("<tr id=" + contactID + "><td><input type='button' class='newContactID' value='Edit'/> <input type='button' value='Delete'/></td><td align=center>" + contactID + "</td><td align=center>" + oEmployee.Title + "</td><td align=center>" + oEmployee.Middlename + "</td><td align=center>" + oEmployee.Lastname + "</td><td align=center>" + oEmployee.Email + "</td><tr>"); // need to hook up editing and deleting function to the newly added rows }
else {
alert("Insert Failed \n" + response.d);
}
}
}
};
//Call the webservice
$.ajax(options);
});
});
</script>
Code for editing and deleting:
$(function() {
$("#tblEmployee > tbody > tr ").each(function() {
var TRID = $(this).attr("id");
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
});
});
What is the best way to approach this? Editing and deleting of records work fine when they're pulled off the database.
Update
This is how the code looks like now, just began dabbling with Jquery a month back, still trying to get my head around it.
$(function() {
$("#tblEmployee > tbody > tr ").live('click', function(e) {
var TRID = $(this).attr("id");
var $target = $(e.target);
if ($target.is('#btnEdit')) {
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
}
else if ($target.is('#btnUpdate')) {
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
}
else if ($target.is('#btnCancel')) {
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
}
else if ($target.is('#btnDelete')) {
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
}
});
});
HTML codes looks like this:
<ItemTemplate>
<tr id='<%# Eval("ContactID") %>'>
<td width="10%">
<input type="button" value="Edit" id="btnEdit"/>
<input type="button" value="Delete" id="btnDelete"/>
<input type="button" value="Update" style="display:none" id="btnUpdate" />
<input type="button" value="Cancel" style="display:none" id="btnCancel"/>
</td>
<td width="10%" align="center"><%# Eval("ContactID")%></td>
<td width="20%" align="center"><%# Eval("Title")%></td>
<td width="20%" align="center"><%# Eval("MiddleName")%></td>
<td width="20%" align="center"><%# Eval("LastName")%></td>
<td width="20%" align="center"><%# Eval("EmailAddress")%></td>
</tr>
</ItemTemplate>
You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.
Here is a same script with php
http://www.amitpatil.me/add-edit-delete-rows-dynamically-using-jquery-php/
// Add new record
$(document).on("click","."+editbutton,function(){
var id = $(this).attr("id");
if(id && editing == 0 && tdediting == 0){
// hide editing row, for the time being
$("."+table+" tr:last-child").fadeOut("fast");
var html;
html += "<td>"+$("."+table+" tr[id="+id+"] td:first-child").html()+"</td>";
for(i=0;i<columns.length;i++){
// fetch value inside the TD and place as VALUE in input field
var val = $(document).find("."+table+" tr[id="+id+"] td[class='"+columns[i]+"']").html();
input = createInput(i,val);
html +='<td>'+input+'</td>';
}
html += '<td><img src="'+updateImage+'"> <img src="'+cancelImage+'"></td>';
// Before replacing the TR contents, make a copy so when user clicks on
trcopy = $("."+table+" tr[id="+id+"]").html();
$("."+table+" tr[id="+id+"]").html(html);
// set editing flag
editing = 1;
}
});