views:

57

answers:

4

I'm wanting to know what the best way to go about creating a list of say, users's statuses (similar to what facebook/twitter has) that is loaded in with PHP when the page loads. But ajax checks for new status updates every 10 seconds or so.

It looks like to me that there are about 2 options: Put the "new items" html in the PHP file that gets called by ajax, and append it to the element containing the status feed. (this also defeats the purpose of JSON)

or

use something like jTemplates. but as far as i can see this option would not be ideal because when the page first loads it has to do an ajax post/get request.

How does everyone else do theirs? I want to do things the best, most 'pro' way!

+1  A: 

It seems as though you're crossing a responsibility boundary. Do you want PHP to be responsible for rendering the HTML? Or do you want javascript/json to be responsible?

Since you want to dynamically update the list, I would use a javascript library like jQuery to perform the ajax request and to handle the json response, and then add new items to the list. There are tutorials for this all over the web.

This will also help keep your sanity in check because when you have to debug (and you WILL have to debug), you only need to work on one set of code using one paradigm: the javascript/json approach, rather than switch mentally between the PHP/HTML and javascript/json side.

Just my $0.02

Bryan Ross
A: 

Ill say you could load the contents into a DIV upon page load.

It doesn't matter if you populate using PHP or javascript to do this on page load.

Then using some sort of javascript sleep script, automatically, every XX amount of seconds reload the DIV html via jQuery with the contents of a PHP page which grabs info about user statuses. Put the function to load the user statuses on an endless loop with the Sleep function pausing before the updates.

http://www.geekpedia.com/KB55%5FHow-do-I-make-a-JavaScript-function-wait-before-executing-%28sleep-or-delay%29.html

I'm guessing the jquery pseudo code would go.

$.get("user_statuses.php", function(data){
  $("div").html(data); // replace the data in the div with user_statuses.php
  sleep(15 seconds); // sleep until next 
});

Make it a recursive call I'm guessing. Don't know if the javascript will crap out eventually but this is an idea.

mmundiff
+1  A: 

I'd use something like this:

$(function() {
    var updateStatus = function() {
        var options = {
            url: "some/address/that/returns/JSON",
            dataType: "json",
            success: function(data, textStatus) {
                // use JSON to update you're markup...
                setTimeout(updateStatus, 10);
            }
        };
        $.ajax(options);
    };
    setTimeout(updateStatus, 10);
});
Drew Wills
+1  A: 

Use APE the Ajax Push Engine, it's written especially for this job. Checkout this Twitter demo to see it in action.

Tom