0

I am using the following code to retrieve data in JSONP format. I need to use it so if no data is returned, I can flag the error. I was using jQuery's ajax(), but it always returns 404 pages as being successful, so I need to use the jquery-jsonp jQuery plug-in on Google Code for error handling.

I borrowed the code from the example on jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event, but I cannot seem to get it to work with my JSON, which is being sent as the MIME type "application/json" from the other server.

$(function(){
    var jsonFeed = "http://othersite.com/feed.json";

    $.jsonp({
        url: jsonFeed,
        dataType: "jsonp",
        timeout: 5000,
        success: function(data, status){
            $.each(data.items, function(i,item){
                console.log("Title: " + item.title);

                if (i == 9) return false;
            });
        },
        error: function(XHR, textStatus, errorThrown){
            console.log("Error Status: " + textStatus);
            console.log("Error Thrown: " + errorThrown);
        }
    });
});

Here is an example of my JSON:

[ { "title" : "My Title" } ]

Can anyone spot the problem?

Community
  • 1
  • 1
Zoolander
  • 2,293
  • 5
  • 27
  • 37
  • 1
    What you have shown as response from the server is JSON, not JSONP. For JSONP it should look like this: `methodName([{"title":"My Title"}])` where `methodName` must be passed as argument. For this the server must support this protocol. Are you sure that the remote server supports it? – Darin Dimitrov May 11 '11 at 14:49
  • What you described is the problem I'm having. I'm using http://wordpress.org/extend/plugins/feed-json/ and wasn't adding the ?callback=methodName. Now, how do I take that and do something with the data in the each() above? – Zoolander May 11 '11 at 15:01

1 Answers1

1

Are you sure "othersite.com" actually supports JSONP. JSON cannot be converted to JSONP by the client. The server needs to support it be wrapping the content with a callback function.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • Yes, I am using the WordPress plug-in Feed JSON: http://wordpress.org/extend/plugins/feed-json/ – Zoolander May 11 '11 at 14:50
  • I think this is the problem (not using callback=). Now how do I retrieve item.title since the data is wrapped in callback()? – Zoolander May 11 '11 at 14:52
  • 1
    You don't need to worry about retrieving that data. jQuery should be able to handle that for you and just give you the data. – Amir Raminfar May 11 '11 at 14:53
  • I added &callback=callback, but now it's returning the same undefined error as well as "callback" is not defined. Any ideas? – Zoolander May 11 '11 at 14:56
  • 1
    callback=? not callback=callback. jQuery documentation states that it will replace the "?" in the url with its callback name. – Amir Raminfar May 11 '11 at 15:09