How do I programmatically refresh a browser How do I programmatically refresh a browser ajax ajax

How do I programmatically refresh a browser


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

  1. Will get updates as soon as an image is uploaded and only when animage is uploaded.
  2. Client will know that image has changed and can do additionalfunctions.
  3. Fully asynchronous and server driven.


You can use AJAX requests to help. For example, what you are doing is polling the server for the image every five seconds. Instead you could poll the server for a new image id and use that id instead of the random number for the source of the image. In this case the src attribute will only change/reload when there is a new image.

<script language="JavaScript"><!--function refreshIt() {   if (!document.images) return;   $.ajax({      url: 'latest-image-id.json',      success: function(newId){          document.images['doc'].src = 'doc.png?' + newId;              }   });   setTimeout(refreshIt, 5000); // refresh every 5 secs}//--></script></head><body onLoad=" setTimeout(refreshIt, 5000)"><img src="doc.png" name="doc">

An alternative is to get a notification from the server when the image changes via a web socket.