I have a simple app script that will send an email whenever my G-sheet is edited. This works fine but it will send an email for every edit in any cell. So, I need to define a specific range as B3:E7 in my Gsheet and the email should trigger only after B3:E7 range is edited. No emails should send for other edits. Please help me on this. I took this code from this tutorial https://spreadsheet.dev/send-email-when-google-sheet-is-edited#:~:text=Step%201%3A%20Create%20your%20spreadsheet,whenever%20your%20spreadsheet%20is%20edited.
//#OnlyCurrentDoc
function processEdit(e) {
var sheet = SpreadsheetApp.getActive();
var rows = sheet.getRangeByName("signups").getValues();
var headerRow = rows.shift();
var editedRow = e.range.getRow();
var template = HtmlService.createTemplateFromFile("Template");
template.headerRow = headerRow;
template.editedRow = editedRow;
template.rows = rows;
var html = template.evaluate().getContent();
MailApp.sendEmail({
to: "myemail#gmail.com ",
subject: "This is test mail",
htmlBody: html
});
}
Try this:
function processEdit(e) {
var sh = e.range.getSheet();
if (sh.getName() == "Your sheet name" && e.range.columnStart > 1 && e.range.columnStart < 6 && e.range.rowStart > 2 && e.range.rowStart < 8) {
var rows = sh.getRangeByName("signups").getValues();
var headerRow = rows.shift();
var template = HtmlService.createTemplateFromFile("Template");
template.headerRow = headerRow;
template.editedRow = e.range.rowStart;
template.rows = rows;
var html = template.evaluate().getContent();
MailApp.sendEmail({
to: "myemail#gmail.com ",
subject: "This is test mail",
htmlBody: html
});
}
}
I got this to work with some minor mods because I didn't want to have to do any extra work and I had the scriptlets for a table already done
GS:
function onMyEdit(e) {
//Logger.log(JSON.stringify(e));
//e.source.toast('Entry');
var sh = e.range.getSheet();
if (sh.getName() == "Sheet0" && e.range.columnStart > 1 && e.range.columnStart < 6 && e.range.rowStart > 2 && e.range.rowStart < 8) {
//e.source.toast("Flag1");
var rows = e.source.getRangeByName("signups").getValues();
//var headerRow = rows.shift();
var template = HtmlService.createTemplateFromFile("ah2");
//template.headerRow = headerRow;
//template.editedRow = e.range.rowStart;
template.rows = rows;
var html = template.evaluate().getContent();
//Logger.log(html);
GmailApp.createDraft("myemail#gmail.com","Subject",null,{htmlBody: html});
}
}
I used Gmail because I just wanted to create a draft
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="tabledata">
<? var vs = rows; ?>
<table>
<? vs.forEach((r,i)=>{ ?>
<tr>
<? r.forEach((c,j)=>{ ?>
<? if(i == 0) { ?>
<th style="padding:2px 5px;font-weight:bold;border:1px solid black;"><?= c ?> </th>
<? } else { ?>
<td style="padding:2px 5px;border:1px solid black;"><?= vs[i][j] ?> </td>
<? } ?>
<? }); ?>
</tr>
<? }); ?>
</table>
</div>
</body>
</html>
Image of email with table
Related
I have problem with upload video file - blob, to our server. I tried solve this by javascript, but I have response 403.
So I tried do it with perl, but nothing happend. I know, that when I try create and save empty txt file with perl, it works (it is upload on server). So I hoped, that it will be similar. But it doesn´t work :(
I´m very basic programmer, please apologize me.
Please, how can I save the file to the server?
Thank you very much.
<html>
<div class="left">
<div id="startButton" class="button">
Start
</div>
<h2>Preview</h2>
<video id="preview" width="160" height="120" autoplay muted></video>
</div>
<div class="right">
<div id="stopButton" class="button">
Stop
</div>
<h2>Recording</h2>
<video id="recording" width="160" height="120" controls></video>
<a id="downloadButton" class="button">
Download
</a>
<a id="uploadButton" class="button" action="upload_ML_v01.pl" method="post" enctype="multipart/form-data">
Upload
</a>
</div>
<script>
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");
let uploadButton = document.getElementById("uploadButton");
let recordingTimeMS = 5000;
function log(msg) {
//logElement.innerHTML += msg + "\n";
}
function wait(delayInMS) {
return new Promise(resolve => setTimeout(resolve, delayInMS));
}
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
log(recorder.state + " for " + (lengthInMS/1000) + " seconds...");
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
let recorded = wait(lengthInMS).then(
() => recorder.state == "recording" && recorder.stop()
);
return Promise.all([
stopped,
recorded
])
.then(() => data);
}
function stop(stream) {
stream.getTracks().forEach(track => track.stop());
}
startButton.addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: false
}).then(stream => {
preview.srcObject = stream;
downloadButton.href = stream;
preview.captureStream = preview.captureStream || preview.mozCaptureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => startRecording(preview.captureStream(), recordingTimeMS))
.then (recordedChunks => {
let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
//upload it to server part start............................
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("video",recordedBlob);
xhr.open('POST', 'video', recordedBlob)
xhr.send(fd);
recording.src = URL.createObjectURL(recordedBlob);
downloadButton.href = recording.src;
downloadButton.download = "RecordedVideo.webm";
log("Successfully recorded " + recordedBlob.size + " bytes of " +
recordedBlob.type + " media.");
})
.catch(log);
}, false);
stopButton.addEventListener("click", function() {
stop(preview.srcObject);
}, false);
</script>
</html>
and perl file:
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use File::Basename;
$|=1; # auto flush
$CGI::DISABLE_UPLOADS = 0;
my $query = CGI->new; # ..global query
my $src_filehandle = $query->upload('recording.src');
my $upld_pathfilename = "video.webm";
open (UPLOADFILE, ">",$upld_pathfilename);
my $totalbytes = 0;
while ( <$src_filehandle> ) {
print UPLOADFILE;
$totalbytes += length;
};
close UPLOADFILE
Your JavaScript code does not look right:
xhr.open('POST', 'video', recordedBlob)
The open method expects a boolean as the third argument, see documentation. You are sending it a blob instead.
Here is an example of how you can send binaray data.
I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}
There is a classic ASP and when Submit button is clicked, it calls Java Script function. The script contains validation of a text box: frmCode and when this validation is passed or the text box is empty, I want to submit form.
However, Set frm = window.document.forms(0) throws an error says "800a01a8|Object_required:_''"
I also tried frm = window.document.forms("form1") but it did not work either.
Any advice would be appreciated. Thank you in advance.
<form Method="post" Action="Test.asp" onSubmit="return OKToSubmit()" id="form1" name="form1" target=_blank>
.....
..... more lines..
.....
<input type="text" id="frmCode" name="frmCode"
style="WIDTH: 248px; HEIGHT: 24px" size=1 maxlength="115">
.....
..... more lines..
.....
<input Type="button" Value="Submit" onClick="OKToSubmit()" id="btnSubmit" name="btnSubmitn">
.....
..... more lines..
.....
<SCRIPT ID=clientEventHandlersVBS type="text/Javascript">
function OKToSubmit(){
var availableCode = new Array();
<%
Dim frm 'reference to form
Set frm = window.document.forms(0)
idx = 0
for idx = 0 to UBound(codeList)-1
%>
availableCode[<%=idx %>] = unescape('<%= Escape(codeList(idx)) %>');
<% next %>
var strCode = document.getElementById('frmCode').value;
var validationFlag = 0;
loopValidation:
for (var i = 0; i < availableCode.length; i++) {
if (strCode == availableCode[i]){
validationFlag = 1;
break loopValidation;
}
}
if (validationFlag == 0 && !(strCode == "")){
alert("Code does not exist. Please check again.");
document.getElementById('frmCode').value = "";
<%
OKToSubmit = False
%>
} else {
<%
OKToSubmit = True
frm.Submit
%>
}
}
</SCRIPT>
see if this gets you what you want:
function OKToSubmit(){
var availableCode = new Array();
var frm = window.document.forms[0];
<%
idx = 0
for idx = 0 to UBound(codeList)-1
%>
availableCode[<%=idx %>] = unescape('<%= Escape(codeList(idx)) %>');
<% next %>
var strCode = document.getElementById('frmCode').value;
var validationFlag = 0;
loopValidation:
for (var i = 0; i < availableCode.length; i++) {
if (strCode == availableCode[i]){
validationFlag = 1;
break loopValidation;
}
}
if (validationFlag == 0 && !(strCode == "")){
alert("Code does not exist. Please check again.");
document.getElementById('frmCode').value = "";
return false;
} else {
frm.submit();
}
}
I moved document.getElementById("form1").submit(); from server side code to client code in Java Script part. Then it is working now. Thank you again for all of your advice.
I think I have a simple bug somewhere but I can't see it!
In my view, I have the following javascript to create a form:
$.ajax({
url:"<?php echo site_url('mycontroller/methodX/'.$ip.'/'.$hardwaremodel);?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='/myapp/index.php/controllerABC/methodABC/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
It's the "submitFormHTML" string that builds the form.
And in my controller I have the following logic to check for the input:
public function methodABC()
{
if($_POST){
echo 'I am here';
$form = $this->input->post();
var_dump($form);
exit();
}
else {
echo "false";
}
It always print the "false". I've also tried using:
print_r($this->input->post());
and
echo $this->input->post('newID');
But I can't seem to get the data from my view into the controller.
Can you see where I'm going wrong? Thanks for the help.
Edit:
The page when rendered, creates the following HTML for the form:
<form method="post" action="/myapp/index.php/switches/changeportvlan/11.11.11.11 /">
<input type='text' id='newVlanID' style='width:5em;height:1.5em'/>
<button type="submit" class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button>
</form>"
The problem was that the textbox is missing a "name" attribute. "id" is not enough!
You need
if ($this->input->post(Null, False)) {
echo "I am here";
$form = $this->input->post(Null, True); ## True for XSS-cleaning, which you probably want.
exit();
}
else {
echo "False";
}
You have to give $this->input->post() arguments. Moreover, never use $_POST in CodeIgniter.
Good luck
I've been trying to use the JsPush Zend progress bar in a Zend MVC application, but have not been successful. I've used the JsPush.php example found on github to create a standalone progress bar test application, but this does not use the Zend MVC framework. When I apply the CSS, HTML, JavaScript, and PHP code from the JsPush example program, I see my progress bar appear (the CSS works) but I don't get any results during my socket write process. I've used the JsPush CSS code verbatim in a css file that is linked to my application so I won't repeat that here. Below are exerpts from my MVC application, the controller code:
protected function _sendFile($job)
{
$fp = fopen($job->source_file, "rb");
if($fp == null || $fileData['size'] == 0) {
$this->view->errorMessage = 'Error - file open failed for ' . $job->source_file;
return false;
}
$this->totalXmitSize = $fileSize;
$this->currentXmitSize = 0;
$progressMessage = '';
$adapter = new Zend_ProgressBar_Adapter_JsPush(array
('updateMethodName' => 'Zend_ProgressBar_Update',
'finishMethodName' => 'Zend_ProgressBar_Finish'));
$progressBar = new Zend_ProgressBar($adapter, 0, $this->totalXmitSize);
while(!feof($fp)) {
$blkSize = ($fileSize > 1024) ? 1024 : $fileSize;
$xmitBuf = fread($fp, $blkSize);
if($xmitBuf === false || !strlen($xmitBuf)) {
$this->view->errorMessage = 'Error - file open failed for ' . $job->source_file;
return false;
}
if($this->_writeData($xmitBuf, $blkSize) == false) {
return false;
}
$fileSize -= $blkSize;
$this->currentXmitSize += $blkSize;
$progress = $this->_calculateXmitProgress();
if($progress < 25) {
$progressMessage = 'Just beginning';
} elseif($progress < 50) {
$progressMessage = 'less than half done';
} elseif($progress < 75) {
$progressMessage = 'more than half done';
} else {
$progressMessage = 'almost done';
}
$progressBar->update($this->currentXmitSize, $progressMessage);
if($fileSize <= 0) {
break;
}
}
fclose($fp);
$xmitBuf = '';
$bufLen = 0;
if($this->_readData($xmitBuf, $bufLen) === false) {
return false;
}
$progressBar->finish();
if(strncmp($xmitBuf, MSG_STATUS_OK, strlen(MSG_STATUS_OK)) != 0) {
$this->view->errorMessage = 'Error - invalid response after file transfer complete';
return false;
}
return true;
}
The view code:
<?php
$this->title = "My Title";
$this->headTitle($this->title);
$this->layout()->bodyScripts = 'onload="startProgress();"';
?>
<p class="errors"> <?php echo $this->errorMessage ?> </p >
<?php echo $this->form->setAction($this->url());
?>
<div id="progressbar">
<div class="pg-progressbar">
<div class="pg-progress" id="pg-percent">
<div class="pg-progressstyle"></div>
<div class="pg-invertedtext" id="pg-text-1"></div>
</div>
<div class="pg-text" id="pg-text-2"></div>
</div>
</div>
<div id="progressBar"><div id="progressDone"></div></div>
The layout.phtml code:
function startProgress()
{
var iFrame = document.createElement('iframe');
document.getElementsByTagName('body')[0].appendChild(iFrame);
iFrame.src = 'MyController.php';
}
function Zend_ProgressBar_Update(data)
{
document.getElementById('pg-percent').style.width = data.percent + '%';
document.getElementById('pg-text-1').innerHTML = data.text;
document.getElementById('pg-text-2').innerHTML = data.text;
}
function Zend_ProgressBar_Finish()
{
document.getElementById('pg-percent').style.width = '100%';
document.getElementById('pg-text-1').innerHTML = 'done';
document.getElementById('pg-text-2').innerHTML = 'done';
}
</script>
</head>
<body <?php echo $this->layout()->bodyScripts ?>>
<div>
<h1><?php echo $this->escape($this->title); ?></h1>
<?php echo $this->layout()->content; ?>
</div>
When this runs I get a ton of JavaScript in the page source, but no progress results:
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":0,"max":3397,"percent":0,"timeTaken":0,"timeRemaining":null,"text":null});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":1024,"max":3397,"percent":30.14424492199,"timeTaken":0,"timeRemaining":0,"text":"less than half done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":2048,"max":3397,"percent":60.28848984398,"timeTaken":0,"timeRemaining":0,"text":"more than half done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":3072,"max":3397,"percent":90.43273476597,"timeTaken":0,"timeRemaining":0,"text":"almost done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":3397,"max":3397,"percent":100,"timeTaken":0,"timeRemaining":0,"text":"almost done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Finish();</script><br />
All of this JavaScript pushes my form out of view. I have spent days on the Zend documentation site and scouring the web to find examples of someone successfully using Zend ProgressBar in a MVC framework application, but can not find any working examples. Thanks in advance for any help.
Well I have been successful in getting a JsPush progress bar to work to some degree, but not 100% correct for my application.
The progressbar works, but the form results end up in the hidden iframe. There is no way to get to the submit buttons on that iframe, so my user has to use the back button to get out of the form.
The only way to get the progress bar to work is to use the target attribute in the form and assign it to the name attribute of the iframe. If I don't use the target attribute, the form scrolls for every call to progressBar->update;. So my form results end up on the parent page several hundred lines scrolled down and the scroll bar never works.
I've tried using the example from the Zend documentation, but it doesn't work. This is my first venture into the Zend framework and it has been very frustrating and disappointing. Not a single response to my original question from 28 days ago.
I had same problem. For me it worked since I did the following steps.
Go to the php.ini and check if the following Data is set in your php.ini.
output_buffering = Off
;output_handler =
zlib.output_compression = Off
;zlib.output_handler =
Then go to class Zend_ProgressBar_Adapter_JsPush and find the Method - which is at the bottom - _outputData. Delete everything in this Method and input
// 1024 padding is required for Safari, while 256 padding is required
// for Internet Explorer. The <br /> is required so Safari actually
// executes the <script />
echo str_pad($data . '', 1024, ' ', STR_PAD_RIGHT) . "\n";
echo(str_repeat(' ',256));
if (ob_get_length()){
#ob_flush();
#flush();
#ob_end_flush();
}
#ob_start();