Quik Tester
Quik Tester

Reputation: 357

jQuery Frame Refresh for Live Updates

I want to work on some Live Updates which is rendered in an iframe. This file called disp.php queries a table "posts" in the database and displays them all from bottom to top. Now when a new entry is added to "posts", I want it to be reflected real-time.

I could achieve it using

<meta http-equiv="refresh" content="10" />  

in the disp.php. But still the constant feel of refreshing is annoying. Now I'm trying to achieve the refresh this way, which doesn't work.

<!DOCTYPE html> 
<html>
<head>
<title>Live Updates</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
</script>
<script> 
function refreshLiveFrame() {
$('body', window.frames['myliveframe'].document).loadIfModified("disp.php");
setTimeout("refreshLiveFrame()", 1000);
}
$(document).ready(function() {
refreshConsole();
});
</script> 
</head>
<body>
<iframe name="myliveframe" src="disp.php">
</iframe>
</body>
</html>

I need a way for a live asynchronous refresh. Anybody's got a workaround? Thanks.

Upvotes: 0

Views: 3854

Answers (2)

satoshi
satoshi

Reputation: 4103

<!DOCTYPE html> 
<html>
    <head>
    <title>Live Updates</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                refresh(); // Calling refresh() on document ready
                window.setInterval("refresh()", 10000); // Calling refresh() every 10 seconds
            });

            function refresh()
            {
                // Asynchonously requesting the content of disp.php
                $.get('disp.php', function(data)
                {
                    // This will be executed when you get the response back from the server
                    $('#posts').html(data);
                });
            }
        </script> 
    </head>
    <body>
        <div id="posts"></div>
    </body>
</html>

Upvotes: 2

satoshi
satoshi

Reputation: 4103

You're trying to achieve your goal using polling, it's a bad practice and, when possible, it's better to avoid it and use pushing instead. Polling means to continue to ask for a resource continuously until it's available. Pushing means that the resource itself will tell you as soon as it's available.

You can use pushing in this case by using jQuery like this:

$('iframe[name=myliveframe]').load(function()
{
    // This will be called every time the page inside the iframe has finished loading
    // $(this).contents() contains the page HTML
    // Use $(this).contents().find('body').html() if you want to read the content of the <body>
});

Upvotes: 1

Related Questions