-1

I've seen other questions about this, but after two hours of trying different things, I still haven't made it work.

Originally, in my website's JS file, I had this:

jQuery.getJSON("https://www.quandl.com/api/v3/datasets/WIKI/FB.json?rows=1&api_key=rzH6xM9oAF1phUUPKxoo", function(data1){
    stocksFB = data1.dataset.data[0][1];
});

In my window.onload, I have:

document.getElementById("stock_area").innerHTML = stocksFB;

However, most of the time the text would show undefined. A few times, it would show the correct information. Thus, after a little research I thought I needed a callback function.

I tried a few different things:

var getStocks = function(){
    //the same query from above here
};

and:

function getStocks(){
    getStocksCallback();
};

function getStocksCallback(){
    //the same query from above
};

also:

function getStocks(function(){
    //the same query from above
});  

and then an extra getStocks() in the onload function for the latter two.

However, the results were always still undefined. Could anyone give me a hint (I'm new to this)?

Yifan
  • 326
  • 3
  • 4
  • 18

2 Answers2

2

You can do something like this if you need a separate function to fill the html :

jQuery.getJSON("https://www.quandl.com/api/v3/datasets/WIKI/FB.json?rows=1&api_key=rzH6xM9oAF1phUUPKxoo", function(data1){
    stocksFB = data1.dataset.data[0][1];
    showStocks(stocksFB);
});

var showStocks = function(stocks){
    document.getElementById("stock_area").innerHTML = stocks;
};

https://jsfiddle.net/dxn991b7/

Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
1

Assign the innerHTML in the callback from the actual get call:

jQuery.getJSON("https://www.quandl.com/api/v3/datasets/WIKI/FB.json?rows=1&api_key=rzH6xM9oAF1phUUPKxoo", function(data1){
    document.getElementById("stock_area").innerHTML = data1.dataset.data[0][1];
});

I'm guessing the reason it works sometimes is because occasionally the call will complete in time, stocksFB gets populated, and then the innerHTML gets called.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    This answer should work and you don't need a callback function because the getJSON success function already waits for a response back from the api call. Make sure your script is wrapped in $( document ).ready(function() { //script here }); – cmartin Jun 02 '16 at 11:59