Pergunta

I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,

Data.php

<?php 
// connect to the database
require_once 'script/login.php';

//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
    . "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = @mysql_query ($query);

if ($result) { //If it ran ok display the records
echo '<div id="feed">';
    while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
        echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote><a href="https://www.facebook.com/dialog/feed?app_id=505747259483458&link=http://www.wisp-r.com/share.php?id=' . $row['PID'] . '&picture=http://www.wisp-r.com/images/app-icon.png&name=Wispr by ' . $row['fbname'] . '&caption=' . $row['pd'] . '&description=' . htmlspecialchars(base64_decode($row['post']), ENT_QUOTES) . '&redirect_uri=http://www.wisp-r.com/share.php?id=' . $row['PID'] . '">Share</a></div></div><br />';
    };
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection

?> 

content.php

<div id="postlist"> FEED GOES HERE.</div>

All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist

It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/

Cheers in advance.

PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck

Foi útil?

Solução

Hopefully you are allowed to use jQuery.

Add to content.php:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">

function getFeed(){
    $.post('Data.php',function(data){
        $("#postlist").html(data);
    });
    setTimeout("getFeed();",2000);
}

window.onload = getFeed();

</script>

getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.

This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.

Outras dicas

If you use KnockoutJS and jQuery, this might be a good starting point:

content.php

<script type="text/javascript">
    $(function() {
        // Define our view model that we will feed to KnockoutJS.
        var viewModel = {
            posts: []
        };

        // We'll use this variable to keep track of the last post we
        // received. When we send our GET request, our php script will be
        // able to see $_GET['last_post_date'] and only return the posts
        // that come after that.
        var last_post_date = null;

        // This is the function that will get called every 2 seconds to
        // load new data.
        var getData = function() {
            $.ajax({
                url: "/data.php",
                data: {
                    last_post_date: last_post_date
                }
            }).done( function( data ) {
                // We'll assume data.php will give us a JSON object that looks
                // like: { posts: [] }

                // Append the new posts to the end of our 'posts' array in our
                // view model.
                viewModel.posts.concat( data.posts );

                // Tell KnockoutJS to update the html.
                ko.applyBindings( viewModel );

                // Store the date of the last post to use in our next ajax call.
                last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
            });

            // In 2 seconds, call this function again.
            setTimeout( getData, 2000 );
        };

        // grab the first set of posts and start looping
        getData();
    });
</script>

<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
     data-bind="template: { name: 'row-template', foreach: posts }"></div>

<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
    <a data-bind="attr: {name: PID}"></a>
    <div id="postsint">
        <a target="_blank" data-bind="
           attr: {
               href: 'http://www.facebook.com/' + fblink
           }
        ">
            <img id="dp" data-bind="
                 attr: {
                     title: fbname,
                     src: 'https://graph.facebook.com/' + fbpic + '/picture'
                 }
            " />
        </a>
        <div id="posttext">
            <!--ko text: post--><!--/ko-->
            <blockquote data-bind="text: pd"></blockquote>
            <a data-bind="
               attr: {
                 href: 'https://www.facebook.com/dialog/feed?' +
                   'app_id=505747259483458&amp;' +
                   'link=http://www.wisp-r.com/share.php?' +
                   'id=' + PID + '&amp;' +
                   'picture=http://www.wisp-r.com/images/app-icon.png&amp;' +
                   'name=Wispr by ' + fbname + '&amp;' +
                   'caption=' + pd + '&amp;' +
                   'description=' + post + '&amp;' +
                   'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
               }
            ">
                Share
            </a>
        </div>
    </div>
    <br />
</script>

data.php

<?php

// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].

$posts = array();
if ( $result ) {
    while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
        array_push( $posts, $row );
    }
}
echo json_encode( array( 'posts' => $posts ) );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top