How to save html form data in txt file using javascript - javascript

I have a html form. I want to store form data in another txt file using javascript.
For ex: I have a html form and store-data.txt file . when user fill the form and hit submit, so data stored in store-data.txt file.
How I will do this using javascript.

Javascript can`t save data on server. JS can save data on clients machine. Data on clients machine can be stored using cookie. But I feel, it isnt an aim. Store data from froms can server side apps, driven like php.

You can use filesaver.js library for a clean implementation or follow along with this codepen It is the quickest.

if you wanted to store input values assign all values in an object then JSON.stringify then throw it to this function to get text file of json
function createTextFile(str){
var file = new Blob([str])
anchor = document.createElement("a")
anchor.href = URL.createObjectURL(file)
anchor.download = "fileName"
anchor.click()
URL.revokeObjectURL(anchor.href)
anchor.remove()
}
var input = "this is a string to test"
createTextFile(input)
and if you wanted to save in server side with php there is function in php
file-put-contents

Related

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

Javascript : Getting the dom image data source and save it to directory

I have an image data here from my console came from DOM displaying it using array
The console data look like this, I perfectly getting this data my problem is how to pass and get that image data into php
["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAuSgpcjBs5Go81S/7+/x/MmaPEm
0:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAEl
1:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAY3U
2:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElE
3:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAEl
Its a long string I did not just continue. I'm not sure if its an object, array or what. Is this possible to pass that value into PHP and then save the image into folder?
var image = [];
$('.dz-image img').each(function(){
image.push($(this).attr('src'));
});
console.log(image);
in general, you're looking at a Data URI - see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs for more info.
in this particular case, you seem to be looking at a base64 encoded PNG file - if you want to upload the PNG to a PHP script on the server, you actually have a TON of options around what happens where (and in what order), but one possible approach is to a) always assume you're dealing w/ base64 encoded PNGs (if you know that not to be true, then you'll have to handle the first two parts of the data URI), b) upload data ($.post() the stuff after the comma) to PHP, c) base64 decode the data on the PHP side
Pass the value into PHP from javascript, consider to use ajax? In my experience, the http-post can transfer Array to PHP directly, like this:
var image = [];
$('.dz-image img').each(function(){
image.push($(this).attr('src'));
});
//console.log(image);
//here, I use jQuery, but you can use any way of ohter javascript framework
$.ajax({
type:'post',
tranditional:true,
url:'saveImage.php',
data:{"iamge":image},
success:function(data){
console.log(image)
}
})
In the php side, if you need to save image address into database, just do it like insert data to database. If you want to save the image into folder, do like this: saveImage.php
<?php
$images = $_POST['image'];
//here, you can code var_dump($image) to console the data you get
foreach($images as $key=>$image){
$image = base64_decode(str_replace('data:image/png:base64,','', $image));
file_put_contents($key.'.jpg', $image);
}
now, have a try?^-^

Press a button to Insert text into html from client.

I use a php to create a guest message board so user can leave message.
I didn't use any database, it is just a text file and append new data.
Is there any easy way to use something like jQuery for user to add new content into the message he left before?
To be clear, I don't want to use any database. Thanks
Create the file with a good structure so the information is easily parseable.
Open file with PHP and parse the information into an object.
Export the object with for example json_encode trough an api
Fetch the object with jQuery
When someone adds a message send it trough jQuery to back-end where you append the message to the file.
Since javascript/jquery is a client language while PHP runs on server. You can use jQuery ajax to send text in a saperate php file via query string where you can append text using PHP fwrite function. here is an idea example to make clear:
jQuery:
var textfield = $('textarea'); //your text area field
var pathToPHP = "Your path to php script/text.php?text="+textfield;
//get text via query string
$.ajax({ URL:pathToPHP , method:"GET", cache:false, type:"HTML" });
//Send text to PHP script using Ajax
You can find further ajax options via jQuery ajax API
PHP:
$text = $_GET['text']; //Get the Text
$txt_file_path = "file.txt"; //Path to text file
$read = fopen($txt_file_path,"w"); //Open Text file in write mode
$new_content = $read." ".$text; //Old Content + New Content
fwrite($read,$new_content); //Rewrite Text file
fclose($read); //Close file
This php code is just for idea and you can refer to fopen and fwrite for complete solution

how to export csv file with filename

I want to export the exist data into csv file. I try to use this code:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
How can I assign filename in the first dialog? Thanks in advance.
update:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name.
For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
I use js code like that:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
As I know, you can specify the filename only in chrome 14+.
Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
Update!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder).
Then send the file names and their path/url to the client via ajax (use a json encoded list for example).
In the ajax callback function: take the list of the files and open each file-url in a separate popup.

I replace HTML using javascript, but that contains a form, want to keep value of that form

I have a page that I have a page I pull from the server every x seconds using some ajax, and then I replace some HTML on the site with the new HTML pulled from the server. The problem has always been that there is a form in that HTML. I want to know is there a way to preserve the value of the form (that the user has entered) when replacing the html in javascript.
Use two callback functions (you should use $.ajax), in the callback before sending (beforeSend(x){ /your code here/; }) you save the parameters (to an array or hashtable): saved = $(element).val(); then in the second callback (use success(x){}) you write them back in. using $(element).val(saved);
var save = document.getElementById('userForm').value;
//replace HTML
document.getElementById('userForm').value = save;
Two ways,
Send and then replace the value in the HTML on the server
Using JavaScript, save it in a session: http://www.webreference.com/authoring/languages/html/HTML5-Client-Side/
I'd say the best solution would be to combine the two and save a session on the server, then load it each time you load the HTML.
-Sunjay03

Categories

Resources