richelliot
richelliot

Reputation: 586

Viewing a webpage in a webpage using XMLHttpRequest

I have built a web app that contains a preview window which shows the content of a html page. Since the html page is being constantly updated, I need the preview window to reflect these changes every 0.5 seconds.

Everything works fine apart from the preview window flashes when it is refreshing. This only happens sometimes and seems to be very temperamental. Most of the time is doesn't flash and the updates to the html page is very fluid.

Here is the code - Can anyone make any suggestions to how to prevent the flashing from occurring?

    //Get the preview data and insert / refresh it in the #preview-fram div
    function refreshinfo(){
        var xmlhttp;
        var id = $.urlParam('id');
        var grid = $.urlParam('grid');                      


        if (window.XMLHttpRequest){
            xmlhttp=new XMLHttpRequest();
        }
        else{
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("preview-frame").innerHTML=xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET","http://webhost:8888/subs-banner-generator/preview?id="+id+'&grid='+grid,true);
        xmlhttp.send();

        }

        setInterval(refreshinfo, 500);  //refresh the data every 0.5 secs

Upvotes: 1

Views: 55

Answers (1)

mplungjan
mplungjan

Reputation: 177786

  1. 500ms is not a lot to give a server
  2. it is not recommended to use setInterval with Ajax
  3. You marked this jQuery, why not use it?

Like this

function refreshinfo(){
    var id = $.urlParam('id');
    var grid = $.urlParam('grid');  
    var url = "http://webhost:8888/subs-banner-generator/preview?id="+id+'&grid='+grid;
    $("#preview-frame").load(url,function() {
      setTimeout(refreshinfo,500); // will load the page again 500ms after successful load
    });
}
$(function() {
  refreshinfo();
});

Upvotes: 1

Related Questions