search

Home  >  Q&A  >  body text

Is it possible to read and display the contents of a txt file every few seconds using HTML?

I have a txt file that is updated with new data every few seconds. It is stored and generated on the Raspberry Pi, which will also act as a server.

I wish to add its content to the html code for display.

It should update without manually reloading the page.

Is there a way to do this? Maybe use AJAX, PHP or something similar?

No need to find/write any code for me as I know it may take a long time. Just point me in the right direction so I can learn how to do it.

P粉529581199P粉529581199477 days ago664

reply all(2)I'll reply

  • P粉477369269

    P粉4773692692023-09-08 00:52:31

    You can use jQuery, $.ajax, $.post or $.get

    Or you can also use XMLHttpRequest for JavaScript programming (old but classic)

    For PHP, you can use readFile (no API required on the server side)

    A little story may help

    Once I used Arduino with WiFi module

    I collect the data using Arduino and then pass the data to esp8266 (WiFi module) and publish to my website using GET method like this: http://mySite.lo /?firstVar=myFirstVar&secondVar=mySecondVar, the server obtains GETdata

    from the URL

    renew:

    Page refresh

    For PHP, you can use header("refresh: 3;")

    For JavaScript, you can use setInterval(location.reload(),3000)

    reply
    0
  • P粉818125805

    P粉8181258052023-09-08 00:08:51

    You can do this using API endpoints and ajax calls on the client side. I drafted some code for you. I set the endpoint URL to /url/to/api.php - you will need to change this URL based on your server settings on the Raspberry Pi.

    You will also need to host an HTML file containing some JavaScript code that polls your API every few seconds. I set it to execute every 5 seconds, using setInterval.

    <script>
    // 客户端代码(JavaScript)- 应该放在</body>标签之前
    (async () => {
        setInterval(async () => {
            const data = await fetch("/url/to/api.php").then(response => response.text());
            document.getElementById("#htmlElementWithThisId").innerHTML(data);
        }, 5000);
    })()
    </script>
    
    // 在HTML中,您必须有一个具有id为"htmlElementWithThisId"的元素 - 这是内容将显示的位置
    
    <div id="htmlElementWithThisId"></div>

    Finally, in your api.php file, you will read your file and "echo" the contents of the file on every request.

    reply
    0
  • Cancelreply