10

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.

<html>
   <head>
      <title>textbox</title>
      <script type="text/javascript">
         function readBOX() {
            var txtinput = document.getElementById('txtinput').value;
            document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
         }
      </script>
   </head>
   <body>
      <p> Type</p>
      <input type="text" id="txtinput" />
      <input id="open" type="button" value="READ" onClick="readBOX()" />
      <form>
         <textarea name="text" rows="20" cols="70">loaded text here</textarea>
      </form>
   </body>
</html>
2

5 Answers 5

11

You have to use something like its posted in this Answer

jQuery

$(document).ready(function() {
   $("#open").click(function() {
       $.ajax({
           url : "helloworld.txt",
           dataType: "text",
           success : function (data) {
               $("#text").text(data);
           }
       });
   });
}); 

Read more on the jQuery Documentation of .ajax()

Non jQuery

I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;

But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia

Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object

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

11 Comments

Please do not downvote without comment. Additional information about fileaccess from JS can be found on this page
I downvote people who answer with jQuery when the asker wasn't using jQuery. It's true he needs to look into ajax, but I dislike suggesting jQuery solely for that.
Then write in you question that you do not want to use jQuery. I think the jQuery way is the most common and the first approach.
I disagree. I think jQuery is only acceptable if you're already using it, or planning to. And I think you should only recommend it when you know the asker is using it.
using $("#text").val(data) instead of $("#text").text(data) has the advanatge that the text is set even if the user already modified the text in the textarea.
|
4

Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.

<!DOCTYPE HTML>
<html>
   <head>
      <title>textbox</title>
   </head>
   <body>
<form action="process.php" method="post">
      <input type="text" name="name" />
      <input type="submit" />
</form>
   </body>
</html>

Process.php

<textarea name="text" rows="20" cols="70"> 
<?php $name =  $_POST["name"]; echo file_get_contents("$name");?>
</textarea>

Comments

3

This is how I load text into a textarea

Main.css

.textbox{
         font-size: 12px;
         float  : left;
         height : 197px;
         width : 650px; }


Default.html

<!DOCTYPE html>
<html> 
    <head>
        <!-- Charactor set allowed to use -->
        <meta charset="utf-8"/>

        <title>Text from .txt file to TextArea</title>

        <!-- External stylesheet -->
        <link rel="stylesheet" href="main.css" />

        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    </head>
    <body>
       <textarea class="textbox" id="Brief" readonly></textarea>

       <script> $( "#Brief" ).load( "text.txt" ); </script>
    </body> 
</html>

google textarea to find format of text area

Comments

1

One of the easiest way is to request the server to return the pre-filled textarea (Here's an example using PHP):

<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>

Note: Something similar can be done with any server-side scripting language.

In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.

Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):

Pure JS:

if (typeof XMLHttpRequest === "undefined") {
    XMLHttpRequest = function () {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
        catch (e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
        catch (e) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (e) {}
        throw new Error("This browser does not support XMLHttpRequest.");
    };
}

function readBOX() {
    function reqListener () {
        document.forms[0].text.value = this.responseText;
    }

    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";

    var oReq = new XMLHttpRequest();
    oReq.onload = reqListener;
    oReq.open("get", filePath, true);
    oReq.send();
}

But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:

jQuery:

function readBOX() {
    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";

    $.ajax({
        url: filePath
    }).done(function(data){
        document.forms[0].text.value = data;
    });
}

Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.

Hope this helps :)

2 Comments

Do we still have to go through ActiveXObject hell? Aren't all modern browser support XMLHttpRequest?
For older IE versions on XP and prior, I'm afraid so. On modern browsers that is not any concern.
0
window.addEventListener('DOMContentLoaded', (e) => {
    let input = document.getElementById('input');
    
    // load default.txt into input box
    try {
        let fileToLoad = './default.txt';
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open('GET', fileToLoad, false);
        xmlhttp.send();
        input.innerHTML = xmlhttp.responseText;
    } catch(DOMException) {
        input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
    }
});

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.