The feed itself works but with the intervals on it updates itself and when I submit something it refreshes the page and nothing gets saved.
jQuery code:
jQuery(document).ready(function() {
setInterval("showNewStories()", 5000);
});
function showNewStories() {
$.getJSON("post.php", null, function(data) {
if (data != null) {
$("#stories").prepend($("<li><span class=\"story\">" +
data.story + "<br /><span class=\"date\">" + data.date +
"</span></li>").fadeIn("slow"));
}
});}
post.php:
<?php
echo json_encode(array( "story" => $_POST['dataS'],
"date" => date('l jS \of F Y h:i:s A')));
?>
What I want to know is how I can have it like Facebook’s feed where you submit something, it gets added to the feed, and then it stays there even if you refresh.
I’m not a php expert, so I can’t tell if you are already doing this, but the code on the server side should accept a parameter which will tell it what date to load the posts from.
You should then have a variable in the javascript on the client side indicating the date/time of the latest post retrieved. When the page loads, this should be null.
Then, the call to
showNewStorieswould send the variable with the last datetime to the server. On the server, if the variable is passed to the php page, then it will return only the posts where the date time posted is greater than the date/time posted.Then, when you get the response from the server, you can add the posts to your timeline. When you add the last one, you store that date time as the date time that will be passed to the server the next time that
showNewStoriesis called.There is a hole in this logic in that if the resolution of the date time on your server is not fine enough to handle the frequency of the number of posts it receives, you could run into an issue where a post is made at time
x, you retrieve the list up to timex, and then another post is accepted at timex. The next timeshowNewStoriesmakes a call to the server, you will miss the second post made at timex.To make this bullet-proof, you would change the logic on the server to include any posts where the post time is equal to the date time passed in. You would also return a unique id for each post passed back to the client.
Then, on the client-side, when the callback to
getJSONis called, you would include any items where the date time of the post is greater than the time submitted to the server or the date times are equal, and the post id returned from the server isn’t already in the list (I’d recommend including the id of the post in the list as a data attribute).