Can't store data fetched with jQuery JSONP

I'm trying to fetch a bunch of photo data from Flickr via a jQuery AJAX call using JSONP, but I don't want to use the data right away. Instead, I'd like to preserve it for use later. In a complicated case, I'd like to let users perform different queries on the prefetched data. In a simpler case, I'd like to just load the next n images each time the user clicks a button.

Right now, I'm testing just the most basic functionality below, which is adapted from the best answer to this question: JQuery - Storing ajax response into global variable

However, the retrieved JSON data is not getting stored in the jsonData variable as it should. I put the alert statements to debug, and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?

var dataStore = ( function() {
  var jsonData;

  $.ajax({
    type: "GET",
    url: "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
    dataType: "json",
    data: {
      tags: "dog",
      tagmode: "any",
      format: "json"
    },
    success: function(data) {
      jsonData = data;
      alert(jsonData);
    }
  });

  return { getData : function()
  {
      if (jsonData) return jsonData;
      else alert("no data!");
  }};
})();

var stuff = dataStore.getData();

$.each(stuff.items, function(i,item) {
  $("<img/>").attr("src", item.media.m).appendTo("#images");
  if ( i == 3 ) return false;
});

Answers


...and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?

Because ajax calls in general are, by default, asynchronous — and JSONP calls are always asynchronous by their nature (other kinds of ajax calls can be made synchronous, but it's generally a bad idea).

This means your

var stuff= dataStore.getData();

line executes before the JSONP request completes. This is also why it doesn't see anything in jsonData.

You need to move any processing of the JSONP call result into something called from the success callback of the request.


Need Your Help

To have AR support back after creating project with --skip-active-record option in rails 3

ruby-on-rails ruby-on-rails-3

I have created a Rails 3 project with mentioned option. Can I somehow "revert" this option and have active record back as in default, or must I create a new project?

How to create pseudo synchronous download in WP7

silverlight windows-phone-7 asynchronous

I have a class with public DownloadAsync Method inside, that downloads Content over Webclient. I create an Object of that class and call the download Method.

Can I take a snapshot of a website from the command line?

python ruby-on-rails image bash fortran

I am writing documentation for a website database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?