TK123 TK123 - 4 months ago 40
jQuery Question

How to get JSONP to work with jQuery?

I am trying to get some JSONP from the Flickr API to work with:

http://jsfiddle.net/SRc98/

$.getScript('http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats', function(data, textStatus, jqxhr) {
alert(data);
});


The alert gives
undefined
and the console says:

Uncaught ReferenceError: jsonFlickrFeed is not defined


Is there something wrong with the Flickr API response or is there a way to get this to work after all?

http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats

Answer

Try using jQuery.getJSON() instead like:

$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats&jsoncallback=?', function(data, textStatus, jqxhr) {
    alert(data);
});

You can see the Online API Documentation Demo

EDIT:

Live demo added here

// Set the flicker api url here
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

// Set the tag display options
var options = {
  tags: "cats",
  format: "json"
};

// Get json format data using $.getJSON()
$.getJSON(flickerAPI, options)
  .done(OnApiCallSuccess)
  .fail(OnApiCallError);

// Api call success callback function
function OnApiCallSuccess(data) {
  $.each(data.items, function(i, item) {
    $("<img>").attr("src", item.media.m).appendTo("#images");

    // Load only the first 6 images for demo
    if (i === 6) return false;
  });
}

// Api call error callback function
function OnApiCallError(jqxhr, textStatus, error) {
  var err = textStatus + ", " + error;
  console.log("Request Failed: " + err);
}
img {
  height: 100px;
  float: left;
  padding: 0 10px 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="images"></div>