views:

54

answers:

4

I'm using the JQuery getJSON function to get some JSON-formatted data.

The data will be used along with the YouTube JavaScript API: http://code.google.com/apis/youtube/js_api_reference.html

The JSON data is not pulled from YouTube. It's a simple, hand-written list of YouTube Video ID's and Titles which are listed on a CSV. I'm using PHP to read the CSV and create a JSON object.

The root of the problem is that when I put any of the YouTube JavaScript API code within "document.ready", the YouTube code mysteriously ceases to work.

I have gotten the complete player to function (with JSON inclded on the HTML page), but now I am facing this obstacle as I try to externalize the data (use $getJSON). For my player to work, I need to have the JQuery code first and inside document.ready. Next, I need to have the YouTube player code and it should be outside of document.ready.

Here is my failed attempt to get the data returned by $getJSON:

$(document).ready(function(){

 $.getJSON('bar.php', function(data) {
     var baz = data;
            return baz;
 }); // getJSON

}) // ready
console.log("baz: " + baz);

How to I get the value of baz?

A: 

Why can't you do what you want with the returned data within the getJSON function?

$(document).ready(function(){
     $.getJSON('bar.php', function(data) {
          // Use data...
          alert("I'm in your function processing your data");
     }); 
});
Michael Robinson
A: 

jQuery.getJSON is a shorthand for the AJAX call:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

So you will have to work with the data within the callback, or any code that requires that data to be called from within the callback.

$(document).ready(function(){
  $.getJSON('bar.php', function(data) {
    var baz = data;
    console.log(baz);
  }); // getJSON
}) // ready
mhitza
+1  A: 

In this case, you can't, for two reasons.

The first, which could be worked around, is that the scope of the variable is the anonymous function that forms the second argument to the getJSON method.

The second, which is rather harder to deal with, is that Asynchronous JavaScript and XML is Asynchronous. The getJSON method sets a download going, but the script then continues running. The console.log line is reached before baz has been assigned a value.

Any complex program written in JavaScript will be event driven. When you set something in motion (such as an Ajax call), you have to handle the results of that via the callback method.

Do whatever needs to be done in the anonymous function you pass to getJSON (or in another function called from there).

David Dorward
head `->` desk.
Matt Ball