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.
Related
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()
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>
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 });
I've just inherited a site and have moved a copy to a Windows Server 2008 test server. When I test the login process I'm getting a server error:
405 - HTTP verb used to access this page is not allowed.
The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.
I've had a look at the login code and it is using a popover window to show the login form then when it is closed it appears to run jQuery script. This is all happening in the login.html page - here's how it currently looks:
$(document).ready(function() {
$("#myform").validate({
//this is the submit = Log in
submitHandler: function(form) {
$.post('../login.php', $("#myform").serialize(), function(data) {
var theString = (data);
var subString = theString.substr(0, 5);
if (subString == "Error")
//if the string starts with error then, guess what, it's an error!
{
$('#results').html(theString);
} else //open the string as a link, it should be the database entry address returned
{
window.location = theString;
}
});
} //close function(data)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<!-- START ADD THIS FOR LOG IN WINDOW -->
<!-- START Log in window -->
<div id="backgroundPopup"></div>
<div id="popupContact">
<h1> Log In.</h1>
<table width="300" align="center">
<form id="myform" method="POST">
<tr>
<td height="20">
<div align="right"> User Name <input class="" name="username" type="text" size="30" /></div>
</td>
</tr>
<tr>
<td height="20">
<div align="right">Password <input name="password" type="password" size="30" /></div>
</td>
</tr>
<tr>
<td height="5">
</tr>
<tr>
<td align="right" height="20">
<input type="submit" name="action" value="LogIn" class="login_button" />
<!-- class="login_button" style="font-size:11px"
// class="my_password" style="font-size:11px" -->
<!--<a id="popupContactClose">x</a> -->
</form>
</td>
</tr>
<br />
</table>
<div class="error" id="results"> </div>
</div>
<div id="backgroundPopup"></div>
<!-- END Log in window -->
<!-- END ADD THIS FOR LOG IN WINDOW -->
From researching similar issues it appears to be a problem with submitting to a .html page that isn't accepting a POST request, but I can't find the settings to allow this (if this is indeed the actual issue). I can't find any settings so far in the current server that is hosting this successfully without this error message (also running Windows Server 2008).
I'm not looking to make any changes to the code at the moment (e.g. convert to PHP etc) just need to get it running on our test server by allowing a POST request to the login.html page.
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;
?>