I have a txt file that updates with new data every few seconds. It is stored and generated locally on a raspberry pi, which will also act as the server.
I want its contents to be added to and html code for displaying.
It should update without manual reloading of the page.
Is there a way to do this? Maybe with AJAX, PHP, or something along those lines?
Don't have to find/write any code for me, as I understand that it would be rather time consuming. just point me in the right direction so I can learn how to do it.
CodePudding user response:
you can use jQuery
,$.ajax
,$.post
or $.get
or can also use XMLHttpRequest
for javascript (old but gold)
and for php use readFile
(server-side no need for API)
little story may help
once i used arduino with wifi module
i collected the data using the arduino, after that i passed it to esp8266 (the wifi modle) and i posted to my site using GET
methode
like
http://mySite.lo/?firstVar=myFirstVar&secondVar=mySecondVar
and the server took the GET
data from the URL
update: the refresh of page
for php it's header("refresh: 3;")
for js write setInterval(location.reload(),3000)
CodePudding user response:
You could do this using an API endpoint and an ajax call on the client. I sketched up some code for you. I made the endpoint url /url/to/api.php - you would change this to match the server setup on the pi.
You would also need to host a HTML file that has some javascript code that polls your api every few seconds. I set it to do this every 5th second, using setInterval.
<script>
// The client code (javascript) - should be placed right before the </body> tag
(async () => {
setInterval(async () => {
const data = await fetch("/url/to/api.php").then(response => response.text());
document.getElementById("#htmlElementWithThisId").innerHTML(data);
}, 5000);
})()
</script>
// In the html you have to have an element with the id: "htmlElementWithThisId" - this is where the content will be displayed
<div id="htmlElementWithThisId"></div>
Finally in the api.php file you would read your file and "echo" the contents of your file on every request