Search code examples
javascripthtmlgetjson

Two seperate .getjson calls returning NAN, how to fix it?


Followed a tutorial where I could use two seperate .getjson calls, where the first one will execute to then multiply by data from the next data call, however, it is simply returning NAN as a value, what have I written wrong?

$.getJSON( "https://api.coinmarketcap.com/v1/ticker/raiblocks/", function( data ) {
  $.getJSON("https://api.fixer.io/latest?base=USD", function (data2) {
    change['rai-usd-cmc'] = data[0]["price_usd"] * data2["GBP"];
    $(".change-rai-usd-cmc").text(change['rai-usd-cmc']);
    $(".change-rai-usd-cmc").text(parseFloat(change['rai-usd-cmc']).toFixed(2));
    loader(false)
    updateData()
  });
});

Trying to multiply data from the first execution with the second getjson call.

Thanks a lot in advance.


Solution

  • I debugged your code and saw that "GBP" key is present within data2.rates object not in data2. So the value of data2["GBP"] is undefined. For this reason, it returns NAN as value. So you can rewrite your code with data2.rates["GBP"] instead of data2["GBP"].

    Here I attach the code.

       $.getJSON( "https://api.coinmarketcap.com/v1/ticker/raiblocks/", function( data ) {
      $.getJSON("https://api.fixer.io/latest?base=USD", function (data2) {
        change['rai-usd-cmc'] = data[0]["price_usd"] * data2.rates["GBP"];
        $(".change-rai-usd-cmc").text(change['rai-usd-cmc']);
        $(".change-rai-usd-cmc").text(parseFloat(change['rai-usd-cmc']).toFixed(2));
        loader(false)
        updateData()
      });
    });