I have three computers; Server
, Client
and Viewer
. I am in control of the server and the viewer.
Client
connects to the Server
and is presented with a webpage.Viewer
is a computer totally without user interaction - there is no keyboard. The Viewer
is always at all time running a web browser, displaying the picture page.My problem now is that even though the picture changes on the server disk, the webpage is not updated. How do I refresh the web browser on the viewer, or part of the webpage?
I know html, css, javascript, php and ajax, but apparently not well enough.
Most people know it can be done by hand by holding the shift key and clicking the “Refresh” (on IE) or “Reload” (on Navigator) buttons.
You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.
There are at least three ways to accomplish this.
Pure HTML
As pointed out by Amitd's comment, in "show.html" add the following <meta>
tag to your document's <head>
element:
<meta http-equiv="refresh" content="5" />
This will automatically refresh the page every 5 seconds. Adjust the value of the content
attribute to the desired number of seconds.
Pure JavaScript:
As pointed out by MeNoMore, document.location.reload()
will refresh the page when you call it.
<script type="text/javascript"> //put this somewhere in "show.html" //using window onload event to run function //so function runs after all content has been loaded. //After refresh this entire script will run again. window.onload = function () { 'use strict'; var millisecondsBeforeRefresh = 5000; //Adjust time here window.setTimeout(function () { //refresh the entire document document.location.reload(); }, millisecondsBeforeRefresh); }; </script>
And as pointed out by tpower AJAX requests could be used, but you'd need to write a web service to return a url to the desired image. The JavaScript to do an AJAX request would look something like this:
<script type="text/javascript"> //put this somewhere in "show.html" //using window onload event to run function //so function runs after all content has been loaded. window.onload = function () { 'use strict'; var xhr, millisecondsBeforeNewImg = 5000; // Adjust time here if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { // try the newer ActiveXObject xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { // newer failed, try the older one xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // log error to browser console console.log(e); } } } if (!xhr) { // log error to browser console console.log('Giving up :( Cannot create an XMLHTTP instance'); } xhr.onreadystatechange = function () { var img; // process the server response if (xhr.readyState === 4) { // everything is good, the response is received if (xhr.status === 200) { // perfect! // assuming the responseText contains the new url to the image... // get the img img = document.getElementById('theImgId'); //set the new src img.src = xhr.responseText; } else { // there was a problem with the request, // for example the response may contain a 404 (Not Found) // or 500 (Internal Server Error) response code console.log(xhr.status); } } else { // still not ready // could do something here, but it's not necessary // included strictly for example purposes } }; // Using setInterval to run every X milliseconds window.setInterval(function () { xhr.open('GET', 'http://www.myDomain.com/someServiceToReturnURLtoDesiredImage', true); xhr.send(null); }, millisecondsBeforeNewImg) }; </script>
Other methods:
Finally, to answer your question to tpower's answer... $.ajax()
is using jQuery to do the AJAX call. jQuery is a JavaScript library that makes AJAX calls and DOM manipulation a lot simpler. To use the jQuery library, you'd need to include a reference to it in your <head>
element (version 1.4.2 used as an example):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
You could also download the "jquery.min.js" and host it locally instead but that would, of course, only change the url you are loaded the script from.
The AJAX function above, when written using jQuery would look more like this:
<script type="text/javascript"> //put this somewhere in "show.html" //document.ready takes the place of window.onload $(document).ready(function () { 'use strict'; var millisecondsBeforeNewImg = 5000; // Adjust time here window.setInterval(function () { $.ajax({ "url": "http://www.myDomain.com/someServiceToReturnURLtoDesiredImage", "error": function (jqXHR, textStatus, errorThrown) { // log error to browser console console.log(textStatus + ': ' + errorThrown); }, "success": function (data, textStatus, jqXHR) { //get the img and assign the new src $('#theImgId').attr('src', data); } }); }, millisecondsBeforeNewImg); }); </script>
As I hope is evident, the jQuery version is much simpler and cleaner. However, given the small scope of your project I don't know if you'd want to bother with the added overhead of jQuery (not that it's all that much). Neither do I know if your project requirements allow the possibility of jQuery. I included this example simply to answer your question of what $.ajax()
was.
I'm equally sure that there are other methods by which you can accomplish refreshing the image. Personally, if the image url is always changing, I'd use the AJAX route. If the image url is static, I'd probably use the <meta>
refresh tag.
I have the exact same application. Just use WebSockets
.
You can start a websocket connection
and the server will inform the Viewer
whenever it gets an update. You can send the updated image through websocket, fully asynchronous without disturbing the display or user interaction.
If you use timers, you will not get quick updates or you will keep refreshing page without use.
Details:
Will need a Websocket server like pywebsocket
or phpwebsocket
.
Client:
Will need HTML5 websocket support, all of the current browsers support it.
Need to register for a message when an image update happens. It is like registering a callback.
Example:
wSocket = new WebSocket('ws://' + serverIP + ':' + serverPort + '/images'); wSocket.onopen = function() { console.log("Primary Socket Connected."); connectedPrimary = true; wSocket.send("sendImageUpdates"); }; wSocket.onmessage = function(evt) { // evt is the message from server // image will be representated as a 64 encoded string // change image with new one $("#image").attr('src', 'data:image/png;base64,' + evt.data); } wSocket.onclose = function() { console.log("Primary Socket Closed."); wSocket = null; }; wSocket.onerror = function(evt) { alert(evt); }
Whenever the server sends an update, the function mapped to wSocket.onmessage
will be called, and you can do whatever you need to do with it.
Server:
Will listen for a connection from client (can be made to support multiple clients). Once a connection is made and the message "sendImageUpdates"
is received, the server will wait for any updates in image. When a new image is uploaded, server will create a new message and send to client.
Pros
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With