Saving a Text File on Server Using JavaScript

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

How to to save txt file on server in HTML/JS?

You can't.

The code you have found is for triggering a download and saving a file to the browser's download directory (client-side).

It would be a serious security risk for a web browser to be able to write to arbitrary files on the server.

Instead, create a web service (using the server side programming language of your choice) and make an HTTP request to it (e.g. by submitting a form or using fetch).

Note that for a sign up system, you are almost certainly going to want to save the data to a database and not to a file (that is still a matter for server-side code though).

How to write a text file on server using JavaScript?

Node.js is the best for this. It gives you acces to your local file system.

Example:

var fs = require('fs');
fs.writeFile("/tmp/test.txt", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});

Javascript: a SIMPLE way to save a text file?



You can do it this way:
<a href="#" id="download">Download</a>

<script>
var fileName = "myfile.txt";
var fileContent = "Page content...";
var myFile = new Blob([fileContent], {type: 'text/plain'});

window.URL = window.URL || window.webkitURL;
var dlBtn = document.getElementById("download");

dlBtn.setAttribute("href", window.URL.createObjectURL(myFile));
dlBtn.setAttribute("download", fileName);
</script>

This will ask the user to save a file called "myfile.txt" where they'd like to. The contents of the file is up to you.

Javascript save variable to .txt file on server and overwrite the.txt content

There is no equivalent, at least in how you're asking. Javascript is client-side; it cannot directly write to a file on a server (unless you're talking about Node, which it doesn't seem like you are). To have Javascript write a file, at best it can make a request to your server side tech (PHP in this case) with information about what to write.

Javascript: Save content to Text File (No complicated Server stuff / HTTPRequest )

$.post is for sending a POST http request.

Client-side javascript doesn't have permission to write to a client machine.

This would be a massive security hole if it did.

However

You've tagged node.js in your question, which can write to the local filesystem:

var fs = require('fs');
fs.writeFile("testFile.txt", "New Content of the File", function(err) {
//done
});

Saving text to a txt file on a html server?

You cannot directly write to a file with Javascript - the security implications of being able to do so do not bear thinking about. What you can do though is ( or one of them anyway ) would be to use Javascript to send the request to save the data to a backend script that does have access and ability to write to files on the server.

For example - using the fetch api to send a request to the PHP script ( it is the same document here for demo but could be an entirely different script ) - the PHP code processes the fetch request and performs one of two tasks - either write data to the file or read from it before sending the response for the fetch callback to process / play with.

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();

$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body

$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? $json->value : false;

switch( $action ){
case 'execute':
$data = array( 'bytes'=>file_put_contents( $file, $value . PHP_EOL, FILE_APPEND ), 'value'=>$value, 'time'=>time() );
break;
case 'count':
$data=array( 'bytes'=>filesize( $file ), 'time'=>time(), 'count'=>sizeof( file( $file ) ) );
break;
default:
http_response_code( 400 );
exit( json_encode('error') );
}

http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:23 /* seems very peculiar hard-coding a value to be written to file!!! */
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
out.innerHTML='';
Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[k,json[k]].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( r=>{ return r.json() })
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
</table>
<output></output>
</body>
</html>

If attempting to record different values ( as a comment suggested ) a minor change to the structure of the data would be advisable so that each ID can be logged properly. The comment I made regarding a database still stands however but perhaps the following might be of use.

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();

$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body

$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;

$data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;

switch( $action ){

case 'execute':
$data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
file_put_contents( $file, json_encode( $data ) );
break;

case 'count':
$value=isset( $data->$value ) ? $data->$value : 0;
$data=new stdclass;
$data->count=$value;
break;

default:
http_response_code( 400 );
exit( json_encode('error') );
}

http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:this.parentNode.parentNode.dataset.id
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
if( out ) out.innerHTML='';

Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[ k, json[ k ] ].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( response => { return response.json() } )
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr data-id=23>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>

<tr data-id=24>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>

<tr data-id=25>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>

<tr data-id=26>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
</table>
<output></output>
</body>
</html>

Delete entry or delete entire contents can be done like so:

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();

$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body

$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;

$data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;

switch( $action ){

case 'execute':
$data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
file_put_contents( $file, json_encode( $data ) );
break;

case 'count':
$value=isset( $data->$value ) ? $data->$value : 0;
$data=new stdclass;
$data->count=$value;
break;

case 'clear':
$data=unlink( $file );
break;

case 'delete':
if( property_exists( $data, $value ) && !empty( $data->$value ) ){
unset( $data->$value );
file_put_contents( $file, json_encode( $data ) );
}
break;

default:
http_response_code( 400 );
exit( json_encode('error') );
}

http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:this.parentNode.parentNode.dataset.id
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
if( out ) out.innerHTML='';

Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[ k, json[ k ] ].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( response => { return response.json() } )
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr data-id=23>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>

<tr data-id=24>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>

<tr data-id=25>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>

<tr data-id=26>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>
</table>
<output></output>
</body>
</html>


Related Topics



Leave a reply



Submit