Currently all working with my jquery $.post actions, successful connections, query and json_encode return to my page. What I’m unable to do(and new to json) is how to display the returned values as a live feed? My current jquery js file is ‘jquery-1.7.2.min.js’ and my code is
$(document).ready(function(){
setInterval(function(){
$.post('query.php', function(pendingReq){
$('#div_id').html(pendingReq);
}), 'json' });
}, 5000
);
pendingReq is my returned data from the query and the current output looks like:
{"[0]":"FirstReq", "[1]":"SecondReq", ...."} based upon my mysql query build of the array
$res = array("[0]"=>var['1']...);
I am very new to using json, and don’t use a lot of javascript, but would like to have the returned data show up in a table, thank you.
My code below works, but for only one row of the mysql query, if two entries exist I get a “Uncaught SyntaxError: Unexpected token {” error in Firebug?? Still returning results as before:
$res = array("req_name"=>$ew_display['req_name'], "date"=>$ew_display['req_dt']);
echo json_encode($res);
$(document).ready(function(){
var table_template = "<table border=1 cellspacing=0 id='results'><tr><th>JTAR #</th><th>JTAR @</th></tr></table>";
$("#testd").html(table_template);
setInterval(function(){
$.post("query.php", {track : 2}, function(pendingReq){
var json = JSON.parse(pendingReq);
var template = "<tr><td>{{req_name}}</td><td>{{date}}</td></tr>";
var new_row = Mustache.render(template, json);
$("#results").append(new_row).fadeIn("slow");
}), "json"
}, 5000);
— EDIT —
Since you’ve got an interval in there, the template can be constant:
Now for the interval, you can parse the result string and render each row:
— END EDIT —
I’m a big fan of Mustache.js (https://github.com/janl/mustache.js), which allows you to separate your data (JSON) from your presentation (HTML table). I’m not a big fan of returning AJAX data from your server pre-formatted as HTML. You can use syntax like this (example only):