Sunday, July 18, 2010

Auto Content Refreshing with jQuery

jQuery is one of the most powerful tools in these days for a web developer
It's so good and so simple! Perfect for us!

So let's show you how to use jQuery to create a simple and efficient auto content refresher.

Html:
<html>
    <head>
        <title>Auto Refreshing Data</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

Javascript:
<script type="text/javascript">
    $(function(){
        var refreshTime = 0;
        
        function refresh(){
            $.get('refresh.php',{},function(callback){
                $('#container').html(callback);
                refreshTime = setTimeout(refresh,15000); // we set the loop
            });
        }

        function cancelRefresh(){
            clearTimeout(refreshTime);
        }
        
        refresh(); // call it for the first time
    });
</script>

Now let's explain it.
$.get() is the jQuery function that send the GET request. $.get has 3 param's, firs is the URL, second params and third is callback.
Something like this:
$.get(url, params,function(callback){...});

The url must redirects to your .php (.html, or any other programming language) that will handle your request, return the result.

The setTimeout function creates a kind of loop, recalling that function every 15000 ms.

To cancel the auto refresh simply call the function cancelRefresh();

Note: You may use $.get, $.post or even $.load.

No comments:

Post a Comment