Dédi
Dédi

Reputation: 145

Create a loop for read a text file or real time changes

So, what I did it's to collect an information from a text file, and then transform that into text on the html page. Here's the code:

HTML:

<div id="text" class="text"></div>

JavaScript:

var text_print = new XMLHttpRequest();
        text_print.open("GET", "file.txt", true);
        text_print.onload = function (){
        document.getElementById("text").innerHTML=text_print.responseText;
        text_print.send(null);

What I need to do now, it's to make this script run every second.
The file.txt in my server changes constantly, so I need that the information printed on screen change when the file changes.
Thank you.

Upvotes: 1

Views: 1498

Answers (1)

willicab
willicab

Reputation: 64

This is not the most efficient way to do it, but if you still decide to continue, this can help you.

window.setInterval(function(){
    var text_print = new XMLHttpRequest();
    text_print.open("GET", "http://localhost/post/file.txt", true);
    text_print.send();
    text_print.onreadystatechange = function () {
        if (text_print.readyState == 4) {
            if(text_print.status == 200) {
                document.getElementById("text").innerHTML=text_print.responseText;
            }
        }
    }
}, 1000);

Upvotes: 1

Related Questions