So I've got my javascript array (var seatsArray = [];), let's say it has some contents. I want to write the contents of that array to a .txt file on the server when the user clicks a button. The text file will not already exist so it needs to be created.
Also, if anyone knows how I could allow the user to specify the name of the text file to be created by typing it in a text area, that would be great.
Any ideas?
Many thanks
John
EDIT:
Added the suggested code, however, nothing happens when I hit save?
<form id="my_form" action="">
<input type="text" id="file_name" rows="1" cols="20">
Save
</form>
<script type="text/javascript">
function submitform();
{
var d = seatsArray.join();
var url = "/txtfiles/"+d + "&file_name=" +
document.getElementById("file_name").value;
document.getElementById("my_form").action = url;
document.getElementById("my_form").method = "POST";
document.getElementById("my_form").submit();
}
</script>
That is all in the body section.
Thanks
You can layout a web form with, among other things, a text field for file name. Then write a Javascript submit event for the form and, in its handler, before send the data build the url with your data.
For the array you can join its data so its converted into a string with a comma separator
var seatsArray = [1,4,5,6];
var d = seatsArray.join(); // "1,4,5,6"
var url = "http://my_site/my_file.php?my_array="+d + "&file_name=" +
document.getElementById("file_name").value;
document.getElementById("my_form").action = url;
document.getElementById("my_form").method = "POST";
document.getElementById("my_form").submit();
Related
I'm new to google script and I'm going crazy trying to do a simple tool.
I created a simple google form with just an email and a file uploader and I need just to insert an email and a pdf, and this should go to the recipient well HTML formatted and whit the pdf attached.
I'm new to this and I tried litterally every syntax using mailApp and Gmail app and the mail comes smooth but the pdf wont.
I know it's just a newbie stupid thing but I can't figure it out at my 74th attempt.
here's the code, I will be grateful forever with someone who can help me!
function sendPDF (e) {
var html = HtmlService.createTemplateFromFile("emailbolladireso.html");
var htmlText = html.evaluate().getContent();
var emailTo = e.response.getRespondentEmail();
var Subject = "---."
var textbody = "---."
var attach = e.response.getItemResponses();
var options = { htmlBody: htmlText};
if(emailTo !== undefined){
GmailApp.sendEmail(emailTo, Subject, textbody, options, )
attachments: attach[1];
}
}
First you have to get the id of your file wich is uploaded by your form to google drive.
You tried with:
var attach = e.response.getItemResponses();
But this will return you an array of objects with all your answers of your form.
From this object you have to extract the id of the uploaded PDF.
If you know the position, for example the first question in your form is for the pdf you can access it with attach[0] if it is e.g. in second position with attach[1], cause arrays index start with 0.
(You could look it also up with a for loop check for the name of the object.
attach[0].getItem().getTitle()
)
With attach[0] you get the next object and from this you get with attach[0].getResponse() finaly the id of your PDF.
attach[0].getResponse()
Now you "load" the file with the given id from google Drive (Make sure you have the permissions for access GoogleDrive)
var file = DriveApp.getFileById(attach[0].getResponse())
You can now attach your file (blob) to your attachments with the right MimeType
attachments: [file.getAs(MimeType.PDF)]
You should also place the attachments in the options of your email.
function sendPDF (e) {
var html = HtmlService.createTemplateFromFile("emailbolladireso.html");
var htmlText = html.evaluate().getContent();
var emailTo = e.response.getRespondentEmail();
var Subject = "Form with PDF"
var textbody = "Your PDF is attached."
var attach = e.response.getItemResponses();
var file = DriveApp.getFileById(attach[0].getResponse())
var options = { htmlBody: htmlText, attachments: [file.getAs(MimeType.PDF)]};
if(emailTo !== undefined){
GmailApp.sendEmail(emailTo, Subject, textbody, options);
}
}
Finaly it should work...
I tested it like this and it works for me.
DON'T PANIC!
Read also the docs -> https://developers.google.com/apps-script/reference/forms/item-response
I'm a server-side dev who's new to front-end development. I've been tinkering around with vanilla Javascript and need to clarify some concepts.
The usecase I'm experimenting with is handling image upload (and mid-air JS-facilitated compression before said upload to server) via JS.
Currently I'm stuck on step one. Imagine the following simple set up:
<form method="POST" action="some_url">
<input type="file" id="browse_image" onchange="compressImage(event)">
<input type="submit" value="Submit">
</form>
My question is:
At what step do I try to pass the image to a JS function (given my goal is to compress it and send it to the server)? Would this happen at the time of image selection (i.e. pressing the browse button), or at the point of pressing Submit? Where do I put the event and how do I proceed from there? A quick illustrative answer with a an example would be great!
I've been trying to do it at the point of image selection (to no avail):
function compressImage(e){
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
console.log(reader);
}
Would be great to get a conceptual walkthrough, alongwith a quick illustrative example. Vanilla JS only, I'm not going to touch JQuery before I get the hang of JS.
In my mind (but it's a bit subjective), you would do it in both places.
User selects a File from your input
You process the file through js
If your processing failed (e.g the file was not an image / corrupted / who knows) you can let the user know directly.
If the processing succeeded, when user clicks submit, you overwrite the default behavior of your form, and send a FormData containing your new File/Blob instead of the original one.
var toSend = null, // here we will store our processed File/Blob (the one to send)
browse_image = document.getElementById('browse_image');
// when user selects a new File
browse_image.onchange = process_user_file;
// when user decides to send it to server
document.querySelector('form').onsubmit = overwrite_default_submit;
// grab the file from the input and process it
function process_user_file(evt) {
// since we attached the event listener through elem.onevent,
// 'this' refers to the input
var file = this.files[0];
// here do your compression, for demo, we'll just check it's a png file
var reader = new FileReader();
// a FileReader is async, so we pass the actual checking script as the onload handler
reader.onload = checkMagicNumber;
reader.readAsArrayBuffer(file.slice(0,4));
}
// we don't want the real form to be submitted, but our processed File/Blob
function overwrite_default_submit(evt) {
// block the form's submit default behavior
evt.preventDefault();
// create a new form result from scratch
var form = new FormData();
// add our File/Blob
form.append("myfile", toSend, browse_image.files[0].name);
// create a new AJAX request that will do the same as original form's behavior
var xhr = new XMLHttpRequest();
xhr.open('POST', evt.target.action);
// xhr.send(form); // uncomment to really send the request
console.log('sent', toSend);
}
// simply checks if it's really a png file
// for you, it will be your own compression code,
// which implementation can not be discussed in this answer
function checkMagicNumber(evt) {
var PNG = '89504e47';
var arr = new Uint8Array(evt.target.result);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
// some user friendly actions
if(header !== PNG) {
alert('not a png file'); // let the user know it didn't work
browse_image.value = ""; // remove invalid File
sub.disabled = true; // avoid the form's submission
toSend = null; // nothing to send
}
else {
toSend = browse_image.files[0]; // for demo we don't actually modify it...
sub.disabled = false; // allow form's submission
}
}
<form method="POST" action="some_url">
<label>Please select a .png file</label>
<input type="file" id="browse_image" name="myfile">
<input type="submit" value="Submit" disabled id="sub">
</form>
Ps: note that even your original code wouldn't have sent anything, since no input in your form had a name attribute.
I need to create HTML page with JavaScript which can store user information into excel directly. Information can contain user input fields like:
First Name (Datatype: Text)
Last Name (Data Type: Text)
I have tried below code for storing values into CSV but I don't know how to store value in excel sheet.
<hrml>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "D:\\sample.csv";
var file = fso.OpenTextFile(fileLoc, 8, true,0);
file.writeline(passForm.FirstName.value + ',' +
passForm.LastName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20">
Type your last name: <input type="text" name="LastName" size="20">
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
Kindly help me for this "How to write HTML input data into Excel using JavaScript"
Thank you so much in advance.
you can create an automation object (in windows) using ActiveXObject() in your javascript code. example:
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
// a text is stored in the first cell
ExcelSheet.ActiveSheet.Cells(1,1).Value = "Texto1";
// the sheet is saved
ExcelSheet.SaveAs("D:\\TEST.XLS");
// close Excel with the Quit() method of the Application object
ExcelSheet.Application.Quit();
You can generate a semicolon separated var with your data and use the window.open function, here is an example:
var data = '';
data += $('#Name').val() + ';'
data += $('#EmployeeID').val();
data += '\r\n';
window.open( "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(data));
You can also generate a formatted html instead a semicolon separated text.
This one uses ActiveX object to write to files on your PC.
It will work only on IE. This is forbidden in browsers by default.
Here's the "normal" use case and how you would be able to complete this with all browsers:
Get form's data (JavaScript)
Make an AJAX request to the server with the data (JavaScript)
The server should have some
logic to get the data and write it to a file (Excel file) (JavaScript, PHP, Java,
C#, 1000s more....)
If you want it to work everywhere, you should put some efforts to create some server too. You may start the server on your local machine so you'll have files saved locally
Please I need help to edit a txt file in client side, I can't find a good method. I need update the data automatic, without confirmation, like it:
<button onclick="updatefile()">Update</button>
<script>
functiom updatefile(){
var file = "d:\test.txt"
var data = //here any function for load all data from file
...
...
data .= " new data to add";
//here any function for save data in test.txt
.....
}
</script>
Please help me.
You cannot do this in that manner using JS. What you CAN do though is to download it on the client, without having the server intervene by using data urls.
Setting the name of said downloaded file is not cross browser compatible unfortunately...
HTML
<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>
Javascript
// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
if($(this).val()){
// Set the URL by appending the base64 form of your text. Keep newlines in mind
$('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
// For browsers that support it, you can even set the filename of the
// generated 'download'
$('#save').attr('download', 'text.txt');
}else{
$('#save').removeAttr('href');
$('#save').removeAttr('download');
}
});
On my page I have a bunch of file upload fields (all with name="files[]" so it can be processed as a PHP array).
They are all located in one of two divs, lets call them 'div1' and 'div2'.
How can I use javascript so that onSubmit, it checks the file types and all the files in div1 can only be 'pdf', and all the files in div2' can only be 'pdf' or 'doc'?
A simple alert popup box will do (ie. "Files can only be pdf")
Any suggestions?
****************UPDATE*******************
Made a more relevant question: Add a filetype validation to phpmailer?
You can make this:
HTML:
<form method="post" enctype="multipart/form-data" name="form">
<input type="file" name="file" /><br />
<input type="file" name="file" />
<input type="submit" />
</form>
JavaScript:
var fileInput = document.getElementsByName("file");
for(var i = 0, len = fileInput.length; i < len; i++) {
fileInput[i].addEventListener('change',
function(e) {
if(this.files[0].name.match(/\.pdf$/) == null) {
alert('Files can only be PDF.');
return;
}
},
false
);
}
File upload elements are heavily protected in browsers, and JS has minimal access to its contents. Anything dealing with the file itself is pretty much locked off, as any hole in the system could allow a malicious site to steal files from the user's computer.
The easiest workaround is to just put up a small note next to the fields say "PDF Only!" and then use a server-side script to confirm that it is a pdf.
You can address the form element and read the name attribute, then you get the file name and can work with the file extension.
But this may only be used to make it easier to the user - so you can detect wrong file types before the uploading process.
It is NOT a protection in any way.
You can also pass the filestypes expected to the dialog itself. Most file managers and browsers respect it and display only the files of the type you want to choose, but the user can click a dropdown and select "view all files" and pic whatever files he/she want.
This is done with the accept attribute.
If you want to help the user choosing the right file both methods above are appropriate and I would even use them together.
If you want to protect your service from wrong filetypes, you have to evaluate the files server side. A file extension checking is not appropriate, there are php functions available to determine the real mimetype of a file.
You can check on submit for each file upload using this code:
var parts = document.getElementById('myFileField').value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension. Needs to be PDF.');
}
Incorporating work by The Mask,
var fileInputs = document.getElementsByName("files[]");
for (var ele in fileInputs) {
if (ele.parentNode.id = 'div1') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF.');
}
}
else if (ele.parentNode.id = 'div2') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf' && parts[parts.length-1] != 'doc') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF or DOC.');
}
}
}