How to download HTML file using google apps script? - html

Hi everyone,
I have a google apps script where it can read the content of the table in my google sheet and send an email to my Gmail account. The script was run together with a HTML file so that the content inside the email looks nice.
Now, I want to download my HTML file a.k.a HTML template into a google drive folder by using a function in google apps script. The expected output in the downloaded HTML file in the google drive folder will be something as shown in the screenshot below:
<div dir="ltr">
<div>Hello everyone! </div>
<div>
<br>
<div><font color="#000000"><span style="font-family:helvetica">Hope you have a nice day</span> </font></div>
<div>
<br>
<div><b style="background-color:rgb(255,255,255)"><font color="#ff0000" face="times new roman, serif"><font size="3">This is just testing the script only...</font></a></font></b></div>
<div>
<br>
</div>
</div>
<div>
<table cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none">
<colgroup>
<col width="111">
<col width="149">
<col width="148">
<col width="134">
</colgroup>
<tbody>
<tr style="height:33px">
<td style="border:1px solid rgb(0,0,0);overflow:hidden;padding:2px 3px;vertical-align:middle;background-color:rgb(218,46,144);font-size:12pt;font-weight:bold;color:rgb(255,255,255);text-align:center">column1</td>
<td style="border-width:1px;border-style:solid;border-color:rgb(0,0,0) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;background-color:rgb(218,46,144);font-size:12pt;font-weight:bold;color:rgb(255,255,255);text-align:center">column2</td>
<td style="border-width:1px;border-style:solid;border-color:rgb(0,0,0) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;background-color:rgb(218,46,144);font-size:12pt;font-weight:bold;color:rgb(255,255,255);text-align:center">column3</td>
<td style="border-width:1px;border-style:solid;border-color:rgb(0,0,0) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;background-color:rgb(218,46,144);font-size:12pt;font-weight:bold;color:rgb(255,255,255);text-align:center">column4</td>
</tr>
<? for(var i = 0; i < stocks.length; i++) { ?>
<tr style="height:33px">
<td style="border-width:1px;border-style:solid;border-color:rgb(204,204,204) rgb(0,0,0) rgb(0,0,0);overflow:hidden;padding:2px 3px;vertical-align:middle;text-align:center"><?= stocks[i].column1 ?></td>
<td style="border-width:1px;border-style:solid;border-color:rgb(204,204,204) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;text-align:center"><?= stocks[i].column2 ?></td>
<td style="border-width:1px;border-style:solid;border-color:rgb(204,204,204) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;text-align:center"><?= stocks[i].column3 ?></td>
<td style="border-width:1px;border-style:solid;border-color:rgb(204,204,204) rgb(0,0,0) rgb(0,0,0) rgb(204,204,204);overflow:hidden;padding:2px 3px;vertical-align:middle;text-align:center"><?= stocks[i].column4 ?></td>
</tr>
<? } ?>
</tbody>
</table>
</div>
<br clear="all">
<div>
<div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature">
<div dir="ltr">
<div>
<br>
</div>
<br>
<div><font color="#000000"><span style="font-family:helvetica">Take note:
<br>
Hope you can be happy everyday!
</span> </font></div>
</div>
<div>
<div>
<br>
</div>
</div>
</div>
</div>
</div>
</div>
However, inside the downloaded HTML file, instead of a for loop to read through all the column, the for loop will be replaced by all the data in the defined range in my google sheet. I'm not sure whether this is possible or not. Any help or advice will be greatly appreciated
Google sheet link to view the script:
https://docs.google.com/spreadsheets/d/1gqjI_n3CKmiKXFqk1P_tYpXxyTFzipaLdf8DXYDpv8s/edit#gid=0

Although I'm not sure whether I could correctly understand your question, how about the following 2 patterns?
Pattern 1:
In this pattern, your HTML template.html is directly exported as an HTML file.
var html = HtmlService.createTemplateFromFile("HTML template.html").getRawContent();
var folder = DriveApp.getFolderById("###"); // Please set the folder ID you want to use.
var file = folder.createFile("sample.html", html, MimeType.HTML);
console.log(file.getId());
Pattern 2:
In this pattern, your HTML template.html is exported as an HTML file by reflecting the values. In this case, the functions of getData() and getEmailHtml(stockData) are from your script in your provided Spreadsheet. Please be careful about this.
var stockData = getData();
var html = getEmailHtml(stockData);
var folder = DriveApp.getFolderById("###"); // Please set the folder ID you want to use.
var file = folder.createFile("sample.html", html, MimeType.HTML);
console.log(file.getId());
Reference:
getRawContent()

Related

Limit decimal numbers in html and where to put the script

So I’ve got a program that prints a html report with some numbers from within the program.
The output number includes 6 decimals, but I want to limit it to 2 decimals..
I’ve read a bunch of articles about coding it, but lacking basic understanding of this type of coding, I need help to write the code.
The code looks like this within the program:
<HTML>
<P align="center">
<img src="image.png">
</P>
<FONT face="Tahoma" size=4 color="Blue">
<P align="center">Rapport</P>
</FONT>
<FONT face="Arial" size=2 color="Black">
<P align="center"><strong>{Date} {Time}</strong></P>
<TABLE border="1" align="center">
<TR>
<TH bgcolor="lightYellow">Vatn 1</TH>
<TH bgcolor="lightYellow">Vatn 2</TH>
<TH bgcolor="lightYellow">Salt</TH>
</TR>
<TR>
<TD bgcolor="#C6DEFF">{vatn1}</TH>
<TD bgcolor="#C6DEFF">{vatn2}</TH>
<TD bgcolor="#C6DEFF">{salt}</TH>
</TR>
</TABLE>
<button onclick="myFunction()">Prenta síðuna</button>
<script>
function myFunction() {
window.print();
}
</script>
<input type="button" align="center" value="Lukka síðu" onclick="self.close()">
</FONT>
</HTML>
And after printed, ready to open in the browser:
<HTML>
<P align="center">
<img src="image.png">
</P>
<FONT face="Tahoma" size=4 color="Blue">
<P align="center">Rapport</P>
</FONT>
<FONT face="Arial" size=2 color="Black">
<P align="center"><strong>{Date} {Time}</strong></P>
<TABLE border="1" align="center">
<TR>
<TH bgcolor="lightYellow">Vatn 1</TH>
<TH bgcolor="lightYellow">Vatn 2</TH>
<TH bgcolor="lightYellow">Salt</TH>
</TR>
<TR>
<TD bgcolor="#C6DEFF">{1.000000}</TH>
<TD bgcolor="#C6DEFF">{2.000000}</TH>
<TD bgcolor="#C6DEFF">{3.000000}</TH>
</TR>
</TABLE>
<button onclick="myFunction()">Prenta síðuna</button>
<script>
function myFunction() {
window.print();
}
</script>
<input type="button" align="center" value="Lukka síðu" onclick="self.close()">
</FONT>
</HTML>
So as far as I know I need a script to process the number, what should it look like and where in my file do I place it? Also whatever tag the edited number ends up in, how do I insert it in the table?
Thanks in advance 🤓
Are you able to give any more info on the program you are using to do this, please?
At a basic level, (depending on your program) scripts can be put on a webpage in-between <script></script> tags.
Now, by looking at the <td>{number}</td> I would assume it is a template of some kind.
If it can do it, try <td>{nuumber.toFixed(2)}</td>
As it's been mentioned, using toFixed(2) on financial data can round numbers incorrectly.
Out of the scope of these question but this article explains why. (Slightly advance but linked for anyone else wondering why!)
I would suggest a better way but without knowing what you're using and the environment that would be too much assumption.
I'm not sure how the information is bound in HTML, so you can change it after the data is loaded.
you can change this block:
<script>
function myFunction() {
window.print();
}
</script>
to this one; This is not a good method but it works as a trick:
/*Important to know (1)*/
<script src="jquery-3.5.1.min.js"></script>
<script>
function myFunction() {
window.print();
}
setTimeout(() => {
$("td").each((i, e) => {
e = $(e);
let data = e.html().replace("}", "").replace("{", "");
e.html(parseFloat(data).toFixed(2));
});
}, 1000);
</script>
(1) Download JQuery and link the HTML to it.
Also if you do not want to use JQuery you can use pure javascript like this:
<script>
function myFunction() {
window.print();
}
setTimeout(() => {
let tags = document.getElementsByTagName("td");
for (let i = 0; i < tags.length; i++) {
let html = tags[i].innerHTML;
html = html.split("{").join("").split("}").join("")
tags[i].innerHTML = parseFloat(html).toFixed(2);
}
}, 1000);
</script>

Using a variable in the body of a HTML email as URL in a hyperlink

I have a Google script that sends out a HTML email from a spreadsheet.
One cell in the spreadsheet holds an URL that is changeable as it is composed from values of other cells.
In my GS I read this URL into a var.
Now I want to use this var in my HTML code that renders the email so that the email receiver can click on a link that opens this custom URL.
I can not find a solution to replace the fixed URL with a variable that holds my custom URL
Please check the HTML code where it says " "
that's where I'm placing a var, but doing it obviously wrong.
**** Google script*****
var CO_PP = COSheet.getRange(2,11).getValue() ;
var CO_PP_href = ("<a href=\"" + CO_PP + "\">") ; // use a backslash \ to escape the quotation marks.
var EmailBody = HtmlService.createTemplateFromFile(template);
EmailBody.EmailVar1 = CO_Name;
EmailBody.EmailVar2 = CO_Email;
EmailBody.EmailVar13 = CO_PP_href;
var MyHtmlBody = EmailBody.evaluate().getContent()
var EmailSubject = "Credits Order SUCCES .:: CADsherpa Weblink ::."
MailApp.sendEmail(CO_Email, EmailSubject, "Your emailreader does not support HTML." +
" Try opening this message with a different email reader or take contact with info#cadsherpa.com", {htmlBody: MyHtmlBody, attachments: PDF_ToSend });
*******HTML*******
<!-- button start -->
<div>
<p> </p>
<table align="left" border="0" cellpadding="1" cellspacing="1" style="height:10px;width:185px;">
<tbody>
<tr>
<td style="white-space: nowrap; text-align: center; vertical-align: middle; background-color: rgb(51, 102, 255);">
<h3> +<?= EmailVar13 ?>+ <span style="font-size:18px;"> <!-- PROBLEM ON THIS LINE -->
<strong><em><span style="font-family:arial,helvetica,sans-serif;">
<span style="color:#FFFFFF;">Pay with PayPal </span></span></em></strong></span></a></h3>
</td>
</tr>
</tbody>
</table>
<p> </p>
</div>
<!-- button end -->
When using HTML templating in GAS, the variables assigned to the template will be escaped. That means that in your case, if CO_PP_href was set to the expression "<a href=\"" + CO_PP + "\">" the actual tags will not be placed into the HTML, but rather the escaped version (<a href="...">) so that it can be treated as printable "text" within your page.
For your needs, I propose a different solution. You can firstly create the <a> tag inside the html template, and only the href attribute thereof will be set when evaluating the template. The solution would look as follows:
HTML
<!-- button start -->
<div>
<p> </p>
<table align="left" border="0" cellpadding="1" cellspacing="1" style="height:10px;width:185px;">
<tbody>
<tr>
<td style="white-space: nowrap; text-align: center; vertical-align: middle; background-color: rgb(51, 102, 255);">
<h3> <a href="<?= EmailVar13 ?>"> <span style="font-size:18px;">
<strong><em><span style="font-family:arial,helvetica,sans-serif;">
<span style="color:#FFFFFF;">Pay with PayPal </span></span></em></strong></span></a></h3>
</td>
</tr>
</tbody>
</table>
<p> </p>
</div>
<!-- button end -->
GAS
var CO_PP = COSheet.getRange(2,11).getValue() ;
var EmailBody = HtmlService.createTemplateFromFile(template);
EmailBody.EmailVar1 = CO_Name;
EmailBody.EmailVar2 = CO_Email;
EmailBody.EmailVar13 = CO_PP;
var MyHtmlBody = EmailBody.evaluate().getContent()
var EmailSubject = "Credits Order SUCCES .:: CADsherpa Weblink ::."
MailApp.sendEmail(CO_Email, EmailSubject, "Your emailreader does not support HTML." +
" Try opening this message with a different email reader or take contact with info#cadsherpa.com", {htmlBody: MyHtmlBody, attachments: PDF_ToSend });

Google Apps Script: withSuccessHandler running without google.script.run.myFunction() running

Within a Google Sheet, I've created an Apps Script to open an html form in a dialog. Along with some input fields on the form, there are two buttons - Save/Exit and Save/Next.
While the buttons should run different server-side functions, both should close the dialog once the server confirms receipt. However I'm finding that the server functions are not running at all, but withSuccessHandler seems to be triggering anyway!
Abbreviated code:
Code.gs
function newProposal() {
var html = HtmlService.createHtmlOutputFromFile('frmBackground').setHeight(500).setWidth(1000);
SpreadsheetApp.getUi()
.showModalDialog(html, 'New Proposal');
}
function saveBackground(e) {
SpreadsheetApp.getActive().toast("hello");
Logger.log(e);
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Project Data");
var alast = sheet.getRange("A3:A").getValues().filter(String).length;
var inpCell = sheet.getRange("A" + (3+alast))
inpCell.setValue(sheet.getRange("A" + (2+alast)).getValue()+1);
inpCell = sheet.getRange("B" + (3+alast));
inpCell.setValue(e.Opportunity)
}
frmBackground.html
<!DOCTYPE html>
<html>
<body>
<form>
<h2 style="text-align: center;"><span style="color: #800080;">PROJECT BACKGROUND</span></h2>
<p> </p>
<table style="height: 172px;" width="778" cellpadding="10">
<tbody>
<tr>
<td style="width: 187px;">
<p style="text-align: right;"><strong><span style="color: #800080;">Project Start Date:</span></strong></p>
</td>
<td style="width: 187px;"><input name="inp_Start" type="date" /></td>
<td style="width: 188px;"><strong><span style="color: #800080;">Opportunity ID:</span></strong></td>
<td style="width: 188px;"><input name="inp_Opportunity" size="3/" type="text" /> <strong><span style="color: #800080;"> months</span></strong></td>
</tr>
.
.
.
</tbody>
</table>
<p> </p>
<p style="text-align: center;">
<input type="button" value="Save and Return" onclick="google.script.run.withSuccessHandler(google.script.host.close).saveBackground()"/>
<input type="button" value="Save and Continue" onclick="google.script.run.withSuccessHandler(google.script.host.close()).saveBackgroundNext()"/></p>
</form>
</body>
</html>
What I expect to happen:
The code in saveBackground() and saveBackgroundNext() should run. The dialog should not close because I haven't yet written a return value.
What I've also tried:
Eliminating the .withSuccessHandler and just asking the button to run
google.script.run.saveBackground() by itself. No response.
Creating a section with a function in the html that tries to execute google.script.run. No response.
Altering the .withSuccessHandler to remove the () after close. No response, but that is expected because there is no Success message to trigger it.

Generate HTML file with both quote ' and " from R

I need to create an HTML file from R software. The problem is that javascript implies simple quote and styles double quote in the string generated.
cat() function returns a quite good text removing backslashs in front of ". But I did not found how to print it like this in an html file using write.table(Text, "index.html", sep="\t")
Thanks in advance for any help.
NB : I removed a "<" character in front of /script in order to be able to post it =)
For exemple :
Text=paste0('<html>
<script type="text/javascript">',
"function lang1(event) {
var iframe = document.getElementById('id1');
var target = event.target || event.srcElement;
iframe.src = event.target.innerHTML + '.html';
}
/script>",
'<body style="overflow:hidden; margin:0">
<div id="main">
<div id="content">
<table style="border: 0; height:100%;width:100%;">
<tr style="height:5%;">
<td colspan="2" style="text-align:center;">
<h2>',paste0("some text"),'</h2>
</td>
</tr>
<tr>
<td style="width: 10%;font-size:14px;">
<ul onclick="lang1(event);">',
paste('<li>',c("link1","link2"),'</li>',collapse=""),
'</ul>
</td>
<td style="width: 90%;">
<iframe id="id1" width="99%" height="99%"></iframe>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>')
Text=gsub("\n","",Text)
I'm not sure I fully understand the question but whenever I generate html files from text in R, I use the \ character to escape quote marks that are needed in the JavaScript.
Then I open a file connection and use the writeLines function to correctly write my text to the file
Text<-"<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<style>
body {
font-size : 16px;
font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;
}
</style>
</head>
</html>
"
fileConn<-file("mywebpage.html")
writeLines(Text, fileConn)
close(fileConn)
Maybe that will help you.

store data from a form using just HTML

I want to create a form (will be filled by users) and store the data in excel stylesheet without using php just HTML ,is that possible?
I dont want to store data an a database.
I have tried to use google doc but it's not that good because the validation messages are generated depending on the browser language.
The unqualified response of "You can't write a file from HTML" is inaccurate. While you may need to add some "hidden" fields in your HTML (in order to simplify the exporting of only the data requested and not the questions or other text) it is ABSOLUTELY possible to do this. I've done JUST THAT in the code below - and all I use is JavaScript. No Server required, No Database required, No PHP required.
Below is the code and a link to the JSFiddle page where you can see it in action:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function fillHidTable(){
var htqf; //-- hidden field
var rf; //-- retrieved field
for ( var i = 1; i < 5; i++ ) {
rf = "htqf"+i;
document.getElementById(rf).innerHTML = document.getElementById("Q"+i+"CALC").value;
}
tableToExcel('hidTable', 'Analysis Results');
}
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
<title>HTML Form Data to Excel</title>
<style type="text/css" media="screen">
.divCenMid{font-family:Arial,sans-serif;font-size:14pt;font-style:normal;font-weight:700;text-align:center;vertical-align:middle;margin:0;}
.allbdrCenMid{border:.75pt solid windowtext;color:#000;font-family:Arial,sans-serif;font-size:10pt;font-style:normal;font-weight:400;text-align:center;vertical-align:middle;margin:0;}
.allbdrCenTop{border:.75pt solid windowtext;color:#000;font-family:Arial,sans-serif;font-size:10pt;font-style:normal;font-weight:400;text-align:center;vertical-align:top;margin:0;}
.allbdrLtMid{border:.75pt solid windowtext;color:#000;font-family:Arial,sans-serif;font-size:10pt;font-style:normal;font-weight:400;text-align:left;vertical-align:middle;margin:0;}
.allbdrLtTop{border:.75pt solid windowtext;color:#000;font-family:Arial,sans-serif;font-size:10pt;font-style:normal;font-weight:400;text-align:left;vertical-align:top;margin:0;}
</style>
</head>
<body>
<table width= "565px" cellspacing="0" cellpadding="0" style="border-spacing:0;" id="QMSTable">
<col width="25px"/>
<col width="120px"/>
<col width="360px"/>
<col width="60px"/>
<tr>
<td class="divCenMid" colspan = "4"> QMS Assessment</td>
</tr>
<tr>
<td class="allbdrCenMid"> No</td>
<td class="allbdrCenMid"> Criteria</td>
<td class="allbdrLtMid"> Question</td>
<td class="allbdrCenMid"> Score</td>
</tr>
<tr>
<td class="allbdrCenTop"> Q1</td>
<td class="allbdrLtTop"> Quality Unit Independency</td>
<td class="allbdrLtTop"> Do you have the Quality Unit?</td>
<td class="allbdrCenMid">
<input id="Q1CALC" type="text" value="" class="nobdrCenMid" style="overflow:hidden; width:93% " name="Q1CALC"/>
</td>
</tr>
<tr>
<td class="allbdrCenTop"> Q2</td>
<td class="allbdrLtTop"> Apply PICS GMP</td>
<td class="allbdrLtTop"> Which GMP regulation do you use?</td>
<td class="allbdrCenMid">
<input id="Q2CALC" type="text" value="" class="nobdrCenMid" style="overflow:hidden; width:93% " name="Q2CALC"/>
</td>
</tr>
<tr>
<td class="allbdrCenTop"> Q3</td>
<td class="allbdrLtTop"> Deviation or Non-conformance</td>
<td class="allbdrLtTop"> Do you have a deviation or non-conformance procedure?</td>
<td class="allbdrCenMid">
<input id="Q3CALC" type="text" value="" class="nobdrCenMid" style="overflow:hidden; width:93% " name="Q3CALC"/>
</td>
</tr>
<tr>
<td class="allbdrCenTop"> Q4</td>
<td class="allbdrLtTop"> Complaint</td>
<td class="allbdrLtTop"> Do you have a customer complaint procedure?</td>
<td class="allbdrCenMid">
<input id="Q4CALC" type="text" value="" class="nobdrCenMid" style="overflow:hidden; width:93% " name="Q4CALC"/>
</td>
</tr>
</table>
<div id="hidTable" style="display: none">
<table id="testTable">
<caption>Supplier Risk Analysis</caption>
<colgroup></colgroup>
<colgroup></colgroup>
<colgroup></colgroup>
<thead>
<tr>
<th>No.</th>
<th>Question</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>Q1</td>
<td>Do you have the Quality Unit?</td>
<td id="htqf1">-</td>
</tr>
<tr>
<td>Q2</td>
<td>Apply PICS GMP?</td>
<td id="htqf2">-</td>
</tr>
<tr>
<td>Q3</td>
<td>Do you have a deviation or non-conformance procedure?</td>
<td id="htqf3">-</td>
</tr>
<tr>
<td>Q4</td>
<td>Do you have a customer complaint procedure?</td>
<td id="htqf4">-</td>
</tr>
</tbody>
</table>
</div>
<input type="button" onclick="fillHidTable()" value="Export Data to Excel">
</body>
</html>
Here is the JSFiddle link: https://jsfiddle.net/MitchinThailand/LV9vr/
if you want more details feel free to holler.
No, HTML pages cannot write files. You need a server to do this.
The best you can do is generate CSV data in a textarea that the user could then copy and paste to a local file, then load that into Excel.
As it is not possible to save html form data to a file using javascript because of some security reason so for my solution i just use the TCPDF for this.
You can generate a data: URL with the download attribute:
<a download="test.csv" href="data:text/csv,foo,bar,baz">
You'll need to use JavaScript to build such URL from form data and insert/update appropriate link in the document.
To do what you want to do simply it will not be possible without php or some advanced HTML5 local storage.
I've done this by using simple PHP script to have form data get saved to a .txt file and then open the resulting .txt file in Excel and use the text to columns feature.
I have a HTML form which collects a field where people enter their email address. I want the form to post the email address to a text file. Please help! Will award maximum points to the one who will answer me correctly!
2 years ago Report Abuse
Additional Details
Please paste entire code to do this!
2 years ago
Form:
<form method="post" action="nameofyourscripthere.php">
Name: <input type="text" name="name" id="name" />
Email: <input type="text" name="email" id="email" />
<input type="submit" name="submit" value="Send Form" />
</form>
PHP:
Create a new page saved as .php with this code. All you need is the form and the PHP script on the server for this to work :)
<?php
// Get the name they entered in the form
// We'll be naming the file this
$file = $_POST['name'];
// Get the email from the form
$email = $_POST['email'];
// We want the file to be a text file right?
$ex = ".txt";
// Try to open a file named $file$ex (johndoe.txt for example)
// Because this file doesn't exist yet the server creates it
$write = fopen("$file$ex","w");
// Now open the file up again but this time save the email in it
fwrite($write,$email);
// MAKE SURE you close the file!!!
fclose($write);
// The folder that this script is in on the server is where the file we just made was saved
// We can 'rename' it to another folder
// The folder on the server we want to move it to
$data = "../emails/";
// Now put it all together: This example goes out of the folder we're in and into the folder 'emails'
// The new 'name' would be this now (../emails/johndoe.txt): So now the file is moved to where we want for storage
rename ("$file","$data$file$ex");
// The script is done, send the user to another page (Just read the address below and you'll get it)
// Its just an example fyi change to what you want
header('Location: http://YourWebsiteNameHere.com/contactFo…
exit;
?>