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.
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 GET
data
renew:
Page refresh
For PHP, you can use header("refresh: 3;")
For JavaScript, you can use setInterval(location.reload(),3000)
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)- 應(yīng)該放在</body>標(biāo)簽之前 (async () => { setInterval(async () => { const data = await fetch("/url/to/api.php").then(response => response.text()); document.getElementById("#htmlElementWithThisId").innerHTML(data); }, 5000); })() </script> // 在HTML中,您必須有一個(gè)具有id為"htmlElementWithThisId"的元素 - 這是內(nèi)容將顯示的位置 <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.