Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading .txt file into textarea Javascript?

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>
like image 551
Gwa Si Avatar asked Sep 26 '13 06:09

Gwa Si


2 Answers

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

like image 168
Martin Avatar answered Oct 17 '22 06:10

Martin


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>
like image 4
Gwa Si Avatar answered Oct 17 '22 07:10

Gwa Si