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
from the URLGET
method like this: http://mySite.lo /?firstVar=myFirstVar&secondVar=mySecondVar, the server obtainsGET
datarenew:
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.
Finally, in your api.php file, you will read your file and "echo" the contents of the file on every request.