tags:

views:

849

answers:

2

Apologies for asking what's probably a very obvious question, I've been banging my head against this all day + I'm very new to JQuery and JavaScript in general.

I'm running the following:-

<script type="text/javascript">
$(function() {
$.getJSON(
  "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22UTG.L%22)%0A%09%09&amp;format=json&amp;env=http%3A%2F%2Fdatatables.org%2Falltables.env&amp;callback=?", 
  function(data) {

$.each(data.query.results.row, function(index, item){
    $('#quotes')
    .append(
      $('<p/>')
        .append($('<span class="left"/>').text(item.symbol))
        .append($('<span class="right"/>').text('$'+item.price))
      );
    });

  }
);

});
</script>

I get object undefined var name, i = 0, length = object.length; from firebug - can anyone help me out?

+1  A: 

From looking at the JSON response, data.query.results.row is undefined (though data.query.results isn't). So you're looping over an undefined property.

You may read through the response's properties by using console.log(data) in your callback. Then, download and install FireBug for Firefox if you haven't done so already and check the console.

moff
+1  A: 

The JSON structure doesn't know a query.results.row, but a query.results.quote instead. This works:

  console.log(data);
  var quotes = data.query.results.quote;
    for(var q in quotes){
        $('#quotes')
        .append(
          $('<p/>')
            .append($('<span class="left"/>').text(q))
            .append($('<span class="right"/>').text('$'+quotes[q]))
          );
        }
    });

You are not calling a JSON resource, but a JSONP resource. The callback argument of the url should be a function name and you should use $.getScript.

myCallback = function(jsonData){...}    
$.getScript("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22UTG.L%22)%0A%09%09&amp;format=json&amp;env=http%3A%2F%2Fdatatables.org%2Falltables.env&amp;callback=myCallback");
stefanw
Not necessarily. jQuery's getJSON will replace ? with a correct callback and create a script element for you.
moff
Interesting, didn't know that one. Crazy jQuery magic.
stefanw