From my webpage I am making a GET request to a servlet via a button. My servlet reads from a webcam and saves an image file (saved to 'img/frame.jpg'). My webpage then includes a script to read from this file every second, so it's updated on the webpage.
Webpage:
<html>
<body>
<img id='feed' src="img/frame.jpg" />
<form method="GET"
action="startCCTV.do">
<br><br>
<center>
<input type="SUBMIT"? value='Start'/>
</center>
</form>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="js/main.js"></script>
</body>
JavaScript (updated since the question was answered):
window.setInterval(function updateFrame() {
invokeServlet();
}, 1000);
// Preload images.
function refreshImage() {
var image = new Image();
image.src = "img/frame.jpg?" + new Date().getTime();
image.onload = function() {
// Image exists and is loaded.
$("#feed").attr('src', "img/frame.jpg?" + new Date().getTime());
}
}
// Send a GET request to the Servlet, to write a new image from the webcam.
function invokeServlet() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
refreshImage();
}
};
xhttp.open("GET", "startCCTV.do", true);
xhttp.send();
}
I did have an infinite loop in my servlet to continuously write a new image, so the image would be updated on the webpage. However, it doesn't seem like a good way to do it (the image refreshed every 3 or 4 seconds and sometimes didn't appear at all). I think the best way would be to have my GET request in a loop in my updateFrame()
function, and have the servlet write one image per request.
However, I don't know how to make this request in my Javascript, without being redirected to the servlet response once the servlet has completed it's writing process.
How can I make intermittent requests to my servlet without being redirected to a new page (i.e. just have the image refreshed on my page)?