Dal Dal - 2 months ago 15
jQuery Question

getJson with custom Flickr API call generates a parse-error

I spent most of last night trying out the 'getJSON' method in JQuery against the Flickr API. I managed to have a look at some examples from the JQuery docs and managed to make them work, however attempts at reading JSON from my custom API calls failed miserably.

Snippets:

This works:

//JQuery Flickr example code - works!
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&format=json",
function(data) {
$.each(data.items, function(i,item){
alert(item.media.m);
if ( i == 3 ) return false;
});
});


This fails!

//Custom Flickr API Call - nothing?fail?
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=c258d8ae4c29bb74da198c6ac3874671&text=Mclaren&per_page=3&format=json&callback=?&nojsoncallback=1",
function(data) {

alert(data);


}).error(function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown); });


The second API call is a valid resource, it works in the browser/fiddler and I can see the JSON content, but in my JS code an error is raised

"parsererrorError: jQuery18007627279118169099_1345796861535 was not called".


At this point I'm stuck, ultimately my end goal is to process the returned JSON and itterate over each 'photo' object in the nested array so that I can easily access their sub properties during iteration like so:

[photo-instance].id

[photo-instance].owner

[photo-instance].secret
etc...

Any help would be greatly appreciated.

Ref: http://www.flickr.com/services/api/response.json.html

Note: All API keys are for test purposes and will be destroyed soon.

Answer

From Jquery documentation :

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

As your URL contains callback=?, the jQuery getJSON function is waiting for a (dynamically specified) callback call, JSONP style. But as you specified nojsoncallback in the URL, the server sends a standard JSON content as specified in the documentation you provide :

If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.

Remove the callback=? from you URL and you should be fine.

Comments