Skip to main content

Refreshing only one <div> in page with just regular Javascript


If I am not grabbing any information from the server but I want to reload/refresh a div every N seconds how do I do this?



New to javascript: I've tried something like




<script type = 'text/javascript'>
function refresh(){
setTimeout(window.location.reload(), 10000);
}

</script>

<div id='target' onLoad='refresh()'>
<?
var =grab some rapidly changing content from the web
print var
?>
</div>
<div>
some stuff that doesn't get refreshed
</div>



Its not clear to me that I need AJAX if im not getting the new info from the server...so for now i'd like to know how to make it work just in javascript



EDIT: I prefer not to use a library for this basic operation so ideally I wouldn't use jquery, prototype etc. EDIT II: Not sure why people are saying the div isnt changing...the content in it is dynamic it is grabbed (say scraped) from the web...and everytime it goes to grab stuff the stuff has changed at the source...an example could be grabbing search results from twitter which change very rapidly...


Source: Tips4allCCNA FINAL EXAM

Comments

  1. You can make a recursive function that will change the content of your div that will look like it is refreshed. Like a timer method, where every set of time will change the time. I don't know how will you get the data that will load on the div, with this I assume you will handle this part.

    Here's the function

    var gIndex = 1;
    function refreshDiv(){
    document.getElementById('target').innerHTML = "Timer " + gIndex++;
    var refresher = setTimeout("refreshDiv()", 1000);
    }

    <body onLoad="refreshDiv()">
    <div>
    <span>HTML Content</span>
    <div id="target"></div>
    </div>
    </body>


    You will see that a time is set when setTimeout will call again the refreshDiv() so this will behave like reloading the content of the div. Before the refreshDiv() call again, change the value of you div.

    ReplyDelete
  2. OK, so you do need AJAX. Well, not the "X" part, you just need the asynchronous Javascript part. The server can return XML or JSON, but in your case it's simplest to have it just return the blob of HTML you want to put into the div.

    But, you do have to make a roundtrip to the server, because nothing has changed in the browser, only the contents of the page on the server have changed.

    Here's a 30-second tutorial that explains everything. I'll adapt it to what you want here.

    First, on the server side, you already have a PHP script, let's call it "page.php", that returns this whole HTML page. You will need to make a second PHP script, let's call it "div.php", that returns just the contents of the div.

    (You could also have page.php look for a parameter, like $_GET['divonly'], and that way have only one PHP script that handles both jobs. It doesn't matter ... you can do it however you want, just as long as you have a second URL to hit on the server side to retrieve the new content for the div.)

    In the HTML of page.php, you've already got:

    <div id="target"> ... </div>


    And now you've added div.php, which returns only the " ... ", not a full HTML page.

    OK, so now, the Javascript. You don't have to use a library if you don't want to -- what's nice about the libraries is that they take care of all of the cross-browser issues.

    But here's what you want, adapted from the example in pure Javascript:

    var refreshDelay = 10000;

    /* Creates the XMLHTTPRequest object depending on the browser */
    function createRequestObject() {
    var ro;
    if(navigator.appName == "Microsoft Internet Explorer"){
    ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
    ro = new XMLHttpRequest();
    }
    return ro;
    }
    var http = createRequestObject();

    /* Makes the request back to /div.php ... change the URL to whatever
    script you put on the server side to return the contents of the div only */
    function sndReq() {
    http.open('get', '/div.php');
    http.onreadystatechange = handleResponse;
    http.send(null);
    }

    /* Does the work of replacing the contents of the div id="target" when
    the XMLHTTPRequest is received, and schedules next update */
    function handleResponse() {
    if(http.readyState == 4){
    var response = http.responseText;
    document.getElementById('target').innerHTML = response;
    setTimeout(sndReq(), refreshDelay);
    }
    }

    /* Schedules the first request back to the server. Subsequent refreshes
    are scheduled in handleResponse() */
    setTimeout(sndReq(), refreshDelay);

    ReplyDelete
  3. Take a look at jQuery.load(). Note that reload fetch info from the server.

    ReplyDelete
  4. Another way is to use
    "The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services"

    ReplyDelete
  5. Short answer :

    1 . div 'onload' doesn't exist. So you need to register a listener for the page
    load event, or put it in "<body onload='refresh()'"
    2 . function refresh(){
    setTimeout("window.location.reload()", 10000); // note the ""
    }


    Long answer :

    Your page doesn't refresh simply because you're function is never executed. Secondly if you put it as is, the page will get refreshed as soon as the page loads, because of setTimeout(window.location.reload(), 10000);.

    As a side node, using this version of the setTimout function is not recommended, and a better approach is to pass the function as the first parameter

    setTimeout(window.location.reload,1000); // we are passing the function,
    // not the function result


    Hope this will help.

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.