update website so it shows image

This commit is contained in:
2024-12-10 13:29:58 +01:00
parent fea0f19857
commit 480d36393a
5 changed files with 67 additions and 54 deletions

View File

@@ -0,0 +1,57 @@
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll(".btn").forEach(button => {
button.addEventListener("click", function(event) {
event.preventDefault(); // prevents page refresh
// Get the value of the button
const direction = event.target.value;
fetch("/move", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ direction: direction })
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
});
});
// Fetch data from the server
async function fetchData() {
const response = await fetch("/data");
const data = await response.json();
return data;
}
// Parse the data and show it on the website
async function parseData() {
const data = await fetchData();
const sensorDataContainer = document.getElementById("sensor-data");
sensorDataContainer.innerHTML = ""; // Clear previous data
// For each object in JSON array, create a new paragraph element and append it to the sensorDataContainer
for (const [key, value] of Object.entries(data)) {
const dataElement = document.createElement("p");
dataElement.textContent = `${key}: ${value}`;
sensorDataContainer.appendChild(dataElement);
}
}
// Update the image
function updateImage() {
var img = document.getElementById("robot-image");
img.src = "/image?" + new Date().getTime(); // Add timestamp to avoid caching
}
// Fetch and display sensor data every 5 seconds
setInterval(parseData, 1000);
// Update the image every 5 seconds
setInterval(updateImage, 400);
});