toomanyairmiles
toomanyairmiles

Reputation: 6485

jQuery object undefined

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&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&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?

Upvotes: 1

Views: 4042

Answers (2)

stefanw
stefanw

Reputation: 10570

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&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=myCallback");

Upvotes: 2

moff
moff

Reputation: 6503

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.

Upvotes: 2

Related Questions