Tuesday, February 19, 2013

Only update a div in HTML



Below is the example to only update one div in HTML USING JS timing function setInterval
 Part 1: using ajax and jquery to update content posted from test.php
Part 2: Only use Javascript
 <html>
 <head>
<!-- Part 1 For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var cacheData;
var data = $('#bottom-bar').html();
var auto_refresh = setInterval(
function ()
{
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: data,
        dataType: 'html',
        success: function(data) {
            if (data !== cacheData){
                //data has changed (or it's the first call), save new cache data and update div
                cacheData = data;
                $('#bottom-bar').html(data);
            }         
        }
    })
}, 300); // check every 30000 milliseconds
</script>
<!-- Part 2 Only using Javascript-->
            <script langauge="javascript">
                var counter = 0;
                window.setInterval("refreshDiv()", 500);
                function refreshDiv(){
                    counter = counter + 1;
                    document.getElementById("test").innerHTML = "Testing " + counter;
                }
            </script>
</head>
<body>

<div id="bottom-bar">test
</div>

            <div id="test">
                Testing
            </div>
            <div id="staticBlock">
                This is a static block
            </div>
</body>
</html>


test.php
 <?php
echo "Hello World <br />";
$counter = rand();
echo $counter;
?>


Demo

No comments:

Post a Comment