0

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.

Sam Clark
  • 429
  • 3
  • 7
  • 12
  • 1
    You're not doing the jsonp properly. jquery has a specific format it looks for to do a jsonp request: http://stackoverflow.com/questions/2681466/jsonp-with-jquery – Marc B Apr 12 '13 at 21:15
  • I would suggest he also look at http://stackoverflow.com/questions/1678214/javascript-how-do-i-create-jsonp which explains how to create a JSONP interface. – Menelaos Apr 12 '13 at 21:40

1 Answers1

0

Here is an example of a response to JSONP call with callback and how it should be returned (in this case CouchDB):

Request:

http://whatever.com/couchdb/db/2010-07-09T23%3A57%3A38.500000Z?callback=a

Response:

a({
    "_id" : "2010-07-09T23:57:38.500000Z",
    "_rev" : "1-750aa2bc0a40e32120e8f6af49b7e979",
    "timestamp" : 2500,
    "data" : {
        "time" : "2010-07-09T23:57:38.500000Z",
        "audio" : {
            "crowd_score" : 0.012911000000000001,
            "traffic_score" : 0.155251,
            "applause_score" : 0.0,
            "music_score" : 0.22573499999999999,
            "@ID" : "freesound_org_100840",
            "position" : 2.5
        }
    }
});

Try adding a semicolon at the end and the ? _ in your generated response should be removed as it makes Javascript thing there is a comparison happening.

Your response should be like this:

jQuery19107630979726091027_1365800375610([{
                "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"
                }
            }
        ]);

Finally, you could have a look at https://stackoverflow.com/a/1678243/1688441 which is very interesting.

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • Okay. I have it pretty much figured out with a fixed callback using $.ajax. However, since I am routing URL's to PHP files (Ex: /api/posts/add -> /api/add.php), I cannot use GET requests. Is there a way to avoid using a GET based callback? – Sam Clark Apr 12 '13 at 22:00
  • That'd be for using varying callbacks. – Sam Clark Apr 12 '13 at 22:01
  • What do you mean with Routing URLs to PHP files? are you implementing a REST API for post/put etc? – Menelaos Apr 12 '13 at 22:12