Jacoby Yarrow
Jacoby Yarrow

Reputation: 155

How to get file contents of a file automatically with AJAX?

I am using AJAX to get the contents of a file when I press a button(I am very new to AJAX.) , Here's the HTML:

<!DOCTYPE html>
<html>

<head>
  <script>
    function loadXMLDoc() {
      var xmlhttp;

      if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

        xmlhttp = new XMLHttpRequest();

      } else { // code for IE6, IE5

        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

      }

      xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

          document.getElementById("myDiv").innerHTML = xmlhttp.responseText;

        }
      }

      xmlhttp.open("GET", "data.dat", true);
      xmlhttp.send();

    }
  </script>
</head>

<body>

  <div id="myDiv">
    <p>- - -</p>
  </div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>

</html>

And here is the python to change the file(This is not the python code i am using, but it still does the same thing, almost):

from time import *
a = 0

while True:
    print(a)
    file = open("data.dat","w")
    file.write("<p>"+str(a)+"</p>")

    file.close()
    sleep(1)
    a+=1

I would like to get the file contents every second, How would I Do that? Any help is good.

Upvotes: 0

Views: 265

Answers (1)

Erik Berkun-Drevnig
Erik Berkun-Drevnig

Reputation: 2356

You could use setInterval() to periodically run the function which updates your document.

var intervalID = setInterval(loadXMLDoc, 1000); // Every 1s

Upvotes: 1

Related Questions