3

I created a java script file that get the images from flickr. Now I want that data can be accessed globally.

$.getJSON('js/album.json', function(data) {
    var myArray = data.children;
    $.each(myArray, function(i, item) {
        $.each(item.children, function(j, childItem){
            var childName = childItem.name;
            getFlickrImage(childName, handleData, data);
        });
    });
    new_json = data;
});

I want the new_json variable access globally. I tried a lot, after so much search on google I posted here.

3 Answers3

0

Answering your question, remember that any "global variable" is just a member of the window's object (when working on browsers). So you just must use:

//...
window.new_json = data
//...

In order to access "new_json" anywhere on your code.

But remember, global variables are evil :) So I would put it inside another object at least.

As a personal advice, I think you should take a look to Jquery's Promises first, because you can't ensure elsewhere on your code that new_json is properly fulfilled. Or also think other design patterns (module pattern, maybe) in order to make your app cleaner.

tehsis
  • 1,602
  • 2
  • 11
  • 15
0

Some pretty bad answers here so far.

In the asynchronous world of AJAX, you need to do things with callbacks. With AJAX, you never know when (or even if) the data that you've asked for will become available. It depends on things like the clients internet connectivity, latency, your server's speed, traffic etc.

So you have to do it like this:

function doSomeAjaxCall(myCallback) {

  $.getJSON('js/album.json', function(data) {
      var myArray = data.children;
      $.each(myArray, function(i, item) {
          $.each(item.children, function(j, childItem){
              var childName = childItem.name;
              getFlickrImage(childName, handleData, data);
          });
      });
      new_json = data;

      myCallback.apply(window);    

  });

});

doSomeAjaxCall(function() {
  console.log(new_json); //see? it is available globally.
});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Curious, what's up with the downvoter? Admittedly, this isn't the only way to do this, but there's also about ten different ways, this is just an example of one way. – Adam Jenkins Dec 18 '13 at 13:46
-2

You can't. You have to make call synchronously.

See this related question for more information.

Community
  • 1
  • 1
ranjeet
  • 540
  • 7
  • 16