Saving User Output to a Text file - javascript

I am wanting to save user input to a text file that will be stored in my local folder directory with filename as date-time(hh-mm-ss).txt So once the user clicks the "save: button, it'll save the contents to that date-time(hh-mm-ss).txt file
I am learning, so please show me with a little explanation, thank you
Current html:
<form>
Subject:
<input type="text" id="subject" size="20">
<br>
Description:
<textarea id="newDescription" rows="4" cols="50" required spellcheck="true"></textarea>
<br>
Tags:
<input type="text" id="tags" size="20">
<br>
<input type="button" value="Save"
onclick="addDescription(this.form);">
</form>
Current external JS:
// This function accepts user input.
function addDescription(form) {
document.getElementById("info").innerHTML =
form.elements["subject"].value + "<br>" +
form.elements["newDescription"].value + "<br>" +
form.elements["tags"].value + ".";
form.reset();
form.elements["subject"].value
form.elements["newDescription"].value
form.elements["tags"].value;
} // end addDescription
Also, if anyone has a better idea on how to make the appearance of the portion of the html look better on the webpage because as of now the label and text boxes look crushed together!

JavaScript on the client side (in the browser) can't read or write files (imagine how dangerous that would be?).
To write a file you'd need server side technology such as NodeJS (if you want to stick with JS). The client side will need to send the data to your backend (NodeJS).
Instead of giving you copy & paste code, I'll give you direction on how to approach the problem, and resources that will get you there:
Set up a backend with NodeJS. Easiest is to use Express:
https://expressjs.com/
To write files with your backend you can use plain NodeJS. Learn
how to do that here.
Build your form correctly by learning from boilerplate code. A good
framework for building out neat HTML and CSS might be Bootstrap,
or Tailwind.
Post the user's data to your NodeJS backend from your form using the
fetch API.

Related

Extracting text from html and writing out to s3 bucket

I am day 1 fresh using javascript and html. I am simply trying to extract text once a button is clicked and write out that text to an s3 bucket. I have an html file that contains the html and java script function that will extract the text. Now I just need to write that data to s3.
<html>
<body>
<center>
<label for="freeform">Please decribe what you would like photo-ai to create:</label>
<br>
<textarea id="freeform" name="freeform" rows="4" cols="50">
Enter text here...
</textarea>
<input type="button" value="Submit my Application!" onclick="formdata()" />
</center>
</body>
</html>
<script>
function formdata()
{
var free_text= document.getElementById("freeform").value;
}
</script>
I see stuff in Node.js but I am not sure the way I am doing here is possible. Basically I am lost and I am asking for guidance, thanks.
On day one you should definitely learn something else than using AWS S3 SDK to upload objects to S3 bucket, but here are the official SDK with some examples how to make it work:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-examples.html

Submitting a form with a complex structure dynamically generated in Javascript to a PHP script via POST method

I'm trying to figure out the best way to submit a form with a complex structure that is dynamically generated in Javascript to a PHP script via the POST method.
The form has this kind of hierarchical structure:
<div class="item">
<textarea class="subitem_textarea"></textarea>
<input type="text"/>
<input type="text"/>
</div>
<div class="item">
<textarea></textarea>
<input type="text"/>
<input type="text"/>
<input type="text"/>
</div>
The number of items is variable and can't be known in advance since items are created by the user. Each item has one <textarea> field, but a variable number of <input type="text"/> fields, since those are also created by the user.
I need to save the content of the form into a database, in a way that preserves this structure, so the PHP script must be able to know which field belong to which item.
I guess that one way to do this is, on the client side (Javascript + jQuery), to arrange for the fields to be given names in such a way that, on the server side (PHP), I can figure that out. For instance, using Javascript + jQuery, I could arrange for the HTML of the form that is dynamically generated on the client side to be:
<div class="item">
<textarea name="textareas[0]"></textarea>
<input type="text" name="texts[0][0]"/>
<input type="text" name="texts[0][1]"/>
</div>
<div class="item">
<textarea name="textareas[1]"></textarea>
<input type="text" name="texts[1][0]"/>
<input type="text" name="texts[1][1]"/>
<input type="text" name="texts[1][2]"/>
</div>
Then, on the server side, I can just recover the structure in PHP by inspecting the $_POST array. However, I can't help but think that I shouldn't have to bother with naming fields in a particular way, that it should be possible to recover the content and structure of the form in a simpler way.
For instance, in order to make various Ajax calls, I already need to store the content and structure of that dynamically created form in a Javascript object as it's being filled, which I send to the server using JSON.stringify when I make the Ajax call and recover in PHP with json_decode
For instance, if I store the content and structure of the dynamically created form in a Javascript object as it's being filled (which I already have to do anyway in order to make various Ajax calls that require that information), perhaps I can somehow use JSON.stringify to send that object to the PHP script that processes the form and use json_decode to get the correct data structure on the server side without the hassle. In fact, I guess I could even do that with another Ajax call that is made when the user clicks on the submit button, instead of doing it through a regular form submission. But I don't suppose it's the best practice and, since I don't have much experience in web development, I want to know what's the best practice to a form with a complex structure dynamically generated in Javascript to a PHP script via the POST method.
EDIT: Just to clarify, since Bilel pointed out I didn't say what I'm planning to do with the data in the form, the PHP script on the server side is going to store the data in the database in a way that preserves the structure.
That's a detailed Question but you didn't told us How are you going to use these collected Data ?
If it's meant to be stored and displayed, then yes you already found the easiest solution by encoding $_POST data with json.
If for example, you could later need relational functionalities like querying User Ages (those being posted through input fields), then you should think about pre-structuring your data. With jQuery/Javascript functions first into a well formatted Json and later Parse the json on the server side to Insert each input field in it's appropriate Database field.
Even, it's against design conventions and space consuming, I do sometimes store the whole json in a separate field near other structured database records. New DBMS can handle json types...
Just to show you an example, I made this function to store a pre-structured json containing Room Information in a booking system, where we can dynamically add extra rooms:
function jss(){
var json = {};
json.rooms = $('.camera').map(function() {
return {
max : $(this).find(".max").val()
, arrange : $(this).find(".arrang").val()
,kids: $('[name^=enf]', this).map(function() {
return {
age: $(this).val()
};
}).get()
, adults: $('[name^=pers]', this).map(function() {
return {
name: $(this).val()
};
}).get()
};
}).get();
return JSON.stringify(json, null, "\t");
}

Retrieve variable name from an HTML site

I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/

How to parse CSV file and store it's data into database?

I trying to store CSV data to database using onclick function. Unfortunately, I am using php code inside javascript function which is not efficient enough. Therefore, I hope that I can get any suggest or solution to improve efficiency of my project by using javascript instead of php to store CSV data into database.
This is javascript with php code :
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>
}
</script>
This is HTML code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>
what are you trying to do there? I think you are speaking about a PHP in
HTML document. So your PHP code inside your function is interpreted on server. As your PHP code has no output your Javascript function is simply empty. Thus as you have registered your Javascript function as onclick handler just nothing would happen.
Remember that standard Javascript code is interpreted on Client (that means in browser) though you PHP code is interpreted on server. As mentioned in the comments above it is possible to use an AJAX or POST/GET - Request to send data to your server and then write it to your DB or file etc.
Another way to do this directly with Javascript is Node.js - serverside Javascript that is able to write to your Database like PHP can do.
The easiest way for you to do it with your HTML code you presented above is to fill in your
action - attribute
in your
form tag
For example:
<form action="proccessData.php" ...>
...
</form>
Don't forget to remove your onclick - attribute inside form's submit input field.
If you know press your submit button your entire form and its content will be send to http://www.xyz.de/proccessData.php. Inside that file you can work with your form data: In your case two text fields and one file upload field. As you may know you could get to the content of text input field send via post via:
$_POST['<name of field>']
To get your uploaded file and proccess it you could use PHP's global
$_FILE[] - Array
Just refer to PHP's manual on php.net or some other online documentation. There's pretty much to find on the web.
I just give you a helpful link to php.net on how to handle file uploads in a correct and therefor secure manner: http://us2.php.net/manual/en/features.file-upload.php
Once you have read your uploaded file via PHP's global $_FILE[] - array just proccess that file via fgetcsv in your proccessData.php and write it line for line to your database.
Hope that helps! It is really not that hard :)

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories