I am working on a live feed that pulls records from a database. Firebug shows the JSON being returned as the following:
{"newPosts":"<li><span id='message_33'>This is a Test.\nLet me know if it works.<\/span><p class='time' id='time_33'>Apr 14th, 2012 10:13:57 AM<\/p><\/li>","newID":"33"}
I have checked the JSON's validity at JSONLint.com, and it IS in fact valid JSON.
Here is my php code that encodes the JSON object:
$last_id = mysql_real_escape_string($_REQUEST['last_id']);
$q = "SELECT id, post, DATE_FORMAT(post_time, '%b %D, %Y %r') AS post_time FROM feed WHERE post_time > (SELECT post_time FROM feed WHERE id='$last_id')
ORDER BY id DESC LIMIT 10";
$results = mysql_query($q,$db);
$isfirst=1;
while($row=mysql_fetch_array($results)){
if($isfirst){
$last_id=$row['id'];
}
$isfirst=0;
$msg_id=$row['id'];
$message=$row['post'];
$time=$row['post_time'];
$data['newPosts'] .= "<li><span id='message_$msg_id'>$message</span><p class='time' id='time_$msg_id'>$time</p></li>";
}
$data['newID'] .= $last_id;
echo json_encode($data);
Am I going about building my JSON array correctly?
Here is the JQuery that posts to publicfeed.php
var updatePosts;
$(document).ready(function(){
updatePosts = function(){
var last_id = $(".last_id").attr("id");
$.getJSON("../scripts/publicfeed.php?last_id="+last_id,
function(data){
$.each(data, function(i,item){
if(item.newPosts){
$("#updates").prepend(item.newPosts);
//alert(item.newPosts);
}
if(item.newID){
$(".last_id").attr("id",item.newID);
//alert(item.newID);
}
});
});
}
setInterval( "updatePosts()", 10000 );
});
And the HTML
<ol class="timeline" id="updates">
<div class="last_id" id="<?=$last_id?>" style="display:none;"></div>
The reason I use the $.each function is becasue there may be times where there are multiple new posts in the feed since the last update. I have used this method many times before, so I have no idea why it isn't return the JSON to the page. I guess the only thing I am unsure about is if I am building my JSON array correctly in publicfeed.php???
I can't even get it to do a simple alert...
Any help is greatly appreciated.