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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex