DaGammla
DaGammla

Reputation: 23

Dynamically reading text file into page

I'm trying to load a .txt file into my simple html page. I'm very noobish and all the code i got is stolen from stackoverflow.

The text file is in the same folder as the html file and contains some text that I'd like to have shown in a div and not just loaded in at the start but dynamically updated (in a 1 sec interval).

The Page that results from the code is just empty. I am using Chrome 73.

I only use the html file and the txt file. No other files are in the folder.

<html>
 <head>
  <script type="text/javascript">
   setInterval(read,1000);
   function read(){
    jQuery.get('file.txt',function(data){$('#container').html(data);});
   }
   read();
  </script>
 </head>
 <body>
  <div id="container"></div>
 </body>
</html>

I don't know what's wrong with this code. Am I missing libraries? If you came up with a completely new code that would be appreciated as well.

Upvotes: 2

Views: 1045

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22320

what about a simple jQuery Load ?

$("#container").load("file.txt");

http://api.jquery.com/load/

Upvotes: 1

cssyphus
cssyphus

Reputation: 40038

Yes, you are missing the jQuery library. Try it like this and let me know:

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script type="text/javascript">
            function read(){
                jQuery.get('file.txt',function(data){$('#container').html(data);});
                setTimeout(function(){read() },1000);
            }
            read();
        </script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

Reference:

https://stackoverflow.com/a/24320973/1447509

See note in italics at very bottom of this article

Upvotes: 1

Related Questions