11

I want a user of my website to enter some text in a text area and when he submits the form, the text that he entered be stored in a .txt file that is present in same directory of the current web page? I don't have a slight idea how it's done or even if it could be done in JavaScript.

How can it be done?

1
  • 7
    Javascript doesn't have access to the file system like that (in some cases it does). You should be using the serverside to save files etc. Commented Feb 28, 2014 at 6:31

5 Answers 5

12

Yes you can, HTML5 File API has a saveAs API that can be used to save binary data using Javascript. You can generate a .txt file by first getting the data into a canvas and saving it as:

canvas.toBlob(function(blob) {
  saveAs(blob, filename);
});

See this demo, the text file is actually generated in browser without PHP. http://eligrey.com/demos/FileSaver.js/

There is an excellent article written back in 2011 by Eli Grey on html5rocks: http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side

More reading at W3C: Filesaver interface


Edit 2016 Update

My original answer showed an example using the BlobBuilder interface which has since been deprecated and marked as obsolete. It is now recommended to use the Blob Construct to manipulate binary data.

At the time of posting, Blob construct is supported on all major browsers. IE 11, Edge 13, Firefox 43, Chrome 45, Safari 9, Opera 35, iOS Safari 8.4, Android Chrome 49.

Demo:

More reading:

Sign up to request clarification or add additional context in comments.

1 Comment

As far as I can tell, this does not do what the original poster requested. They wanted a file that could be updated and saved to the server, not a file that could be downloaded on the client-side.
4

you cant save file with js in server nor the client system. you need a server side script like php or asp.net to save files to server. but cant save anything other than a cookie to the client system.

Comments

4

You can't. You need some server-side script to access the filesystem of the server such as PHP or Java.

Comments

4

This one might help you.

http://wcetdesigns.com/tutorials/2012/11/01/edit-save-file.html
https://web.archive.org/web/20131210151034/http://wcetdesigns.com/tutorials/2012/11/01/edit-save-file.html

edit.php, file where users can edit using the textarea tag.
<html>
<head>
<script src="http://wcetdesigns.com/assets/javascript/jquery.js"></script>
<script>
function save(){
     var x = $("textarea").val();
     var data = 'c='+x;

     $.ajax({
         type: 'POST',
         url: 'save.php',
         data: data,
         success: function(e){
             $("#s").html(e);
         }
     });
}
</script>
</head>
<body>
<textarea>
<?php

$fn = "blank.html"; //FILE TO BE EDITED (FILENAME EDITABLE)
$file = fopen($fn, "r+"); //OPENS IT
$fr = fread($file, 1000000); //READS IT
fclose($file); //CLOSE CONNECTIONS
echo $fr; //SHOWS THE EDITABLE FILE HERE

?>
</textarea><br>
<input onClick="save()" id="x" type="button" value="Save"><br><br>
<span id="s"></span><br>
<a href="blank.html" target="_new">view file</a>
</body>
</html>
save.php, file where the saving process will take place.
<?php

$c = $_POST["c"]; //TEXT FROM THE FIELD

$f = 'blank.html'; //FILE TO SAVE (FILENAME EDITABLE)
$o = fopen($f, 'w+'); //OPENS IT
$w = fwrite($o, $c); //SAVES FILES HERE
$r = fread($o, 100000); //READS HERE
fclose($o); //CLOSES AFTER IT SAVES

//DISPLAYS THE RESULTS
if($w){
    echo 'File saved';
} else {
    echo 'Error saving file';
}

?> 

Javascript doesn't have access to file system so you must use some server side language like PHP as in the given example

Comments

3

You can send that particular textarea value through ajax by javascript. Then on the server side you can put a code, where you can accept the string and save it in a text file. You cant just do it with Javascript, you need a serverside code..

        //Html
    <textarea id="TextArea"></textarea>

    //javascript
    var dataVal = $('#TextArea').val();
    if(dataVal!="")
    {
    $.ajax({
                url: '/createTextFile',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: dataVal,
                success: function (response) {
                    alert('Success');      
                },
                error: function (xhr) {
                    alert('Error: There was some error while posting. Please try again later.');
                }
            });
    }

    //You can server side code (C#)

    function SaveToTextFIle(text)
    {
        try
        {
            // The using statement automatically closes the stream and calls  
            // IDisposable.Dispose on the stream object. 
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            {
                file.WriteLine(text);
            }
        }
        catch(ex)
        {
            throw ex;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.