I have a PHP backend, which when queried, will return a set of posts in JSON. But, since there are multiple posts, it is in an array. Ex: (The string at the beginning is just a JSONP callback)
jQuery19107630979726091027_1365800375610?_=1365800375611([
{
"content": "Hello",
"time": "1349829544",
"info": {
"email": "test@test.com",
"username": "test",
"first": "Test",
"last": "User",
"id": "2"
}
},
{
"content": "test.",
"time": "1349829535",
"info": {
"email": "test@test.com",
"username": "test",
"first": "Test",
"last": "User",
"id": "2"
}
}
])
Note how the JSON is surrounded by brackets. When I use a jQuery script to call and parse this data, I get the error "Uncaught SyntaxError: Unexpected end of input," pointing me to the last line of data where the bracket is. JS:
$("#getPosts").click(function(){
$.getJSON("http://mysite.com/api/posts/list/byfriends/callback=?", function(data){
$.each(data, function(){
$('#posts').append("<li><p>"+this.content+"</br>By: "+this.info.first+" "+this.info.last+" ("+this.info.email+")");
});
});
});
And finally, here is the PHP sending the JSON:
include('config.inc');
header("Content-type: text/javascript");
$posts = array();
$subscribe = "SELECT subscribed FROM subscribe WHERE subscriber = '{$_SESSION['id']}'";
$query = mysql_query("SELECT * FROM `posts` WHERE (`post_owner` IN ({$subscribe}) OR `post_owner` = {$_SESSION['id']}) ORDER BY `id` DESC");
$num = mysql_numrows($query);
for ($i = 0; $i < $num; $i++) {
$post['content'] = mysql_result($query, $i, 'content');
$post['time'] = mysql_result($query, $i, 'timestamp');
$post['info'] = getInfo_other(mysql_result($query, $i, 'post_owner'));
array_push($posts, $post);
}
echo $callback."("json_encode($posts, JSON_PRETTY_PRINT).")";
The callback variable is functioning. I have a simple PHP router setup that handles that.