Anthony
Anthony

Reputation: 65

Outputting constantly changing text file data onto a webpage via Javascript

I have a python script that updates my output.txt file every 2 seconds. I'm able to output the txt file data to a webpage but for some reason it will not update until I restart the server. What I'm trying to do is have the webpage update the output.txt file data every 2 seconds. Here's what I'm using right now:

var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');

function loadFile() {
    reader.open('get', 'output.txt', true); 
    reader.onreadystatechange = displayContents;
    reader.send(null);
    reader.onreadystatechange = outputData();
}

function displayContents() {
    if(reader.readyState==4) {
        var el = document.getElementById('main');
        el.innerHTML = reader.responseText;
    }
}

function outputData() {
    var refresh = 2000;
    update = setTimeout('loadFile()', refresh);
}

What I'm attempting to do is have the outputData function call the loadFile function every 2 seconds which is meant to re-read the output.txt file's updated data. Any help would be appreciated as I'm new to web programming. If it matters I'm running Apache on a Raspberry Pi 3 to create the webpage.

EDIT: Here is my python code in case it might be causing the problem.

#!/usr/bin/env python
import time
from datetime import datetime

var = datetime.now().time()

while True:
    print(var)
    with open("output.txt", "w") as txtfile:
        print(var, file=txtfile)
    var = datetime.now().time()
    time.sleep(2)

Upvotes: 0

Views: 763

Answers (1)

guest271314
guest271314

Reputation: 1

You are calling outputData() immediately instead of referencing the function to be called at readystateschange event. Remove

reader.onreadystatechange = outputData();

call outputData() within displayContents call. Call loadFile() at window load event.

window.onload = function() {
  var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');

  function loadFile() {
    reader.open('get', 'output.txt', true);
    reader.onload = displayContents;
    reader.send(null);
  }

  function displayContents() {
    if (reader.readyState == 4) {
      var el = document.getElementById('main');
      el.innerHTML += reader.responseText + "<br>";
      outputData();
    }  
  }

  function outputData() {
    var refresh = 2000;
    update = setTimeout(loadFile, refresh);
  }

  loadFile()
}

plnkr http://plnkr.co/edit/EKh2DsmxtbzMYMlt1F4V?p=preview

Upvotes: 1

Related Questions