user967451
user967451

Reputation:

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

Upvotes: 0

Views: 1261

Answers (2)

palaѕн
palaѕн

Reputation: 73966

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>

Upvotes: 3

harrybvp
harrybvp

Reputation: 2505

JQuery's getScript hardcodes data parameter to null, and automatically evaluates the retrieved script.
I think documentation is wrong. Good thing is that you probably just wanted to evaluate the script anyway and you dont need the callback at all.

For your Case:-
script retreived from your URL is indeed getting evaluated but currently there is no definition for function jsonFlickrFeed().so that's why undefined error is shown. You need to include some JS file which has its definition.

Upvotes: 0

Related Questions