2

I would like to thank you for any help you can offer.

With all of the cryptocurrency craze I wanted to make a USD to DOGE converter for a website I had in mind. This is my first time using jQuery.

The script converts $11 USD (price of service I want to offer) and converts it to Bitcoin. It then converts Bitcoin ($11 USD worth) to Dogecoin.

The problem is, about half of the time, the number that the script returns and adds to the "price" h1 text is 0. How can I give the JSON parse more time so that the script doesn't show 0 as the amount? Or is there another problem I am unaware of?

var $BTCUSD = '';
var $BTC = '';
var $DOGEBTC = '';
var $DOGE = '';
var $price = '';

$.getJSON('http://www.cryptocoincharts.info/v2/api/tradingPair/btc_usd', function(btc) {
        $BTCUSD = btc.price;
        $BTC = 11 / $BTCUSD;
    });

$.getJSON('http://www.cryptocoincharts.info/v2/api/tradingPair/doge_btc', function(doge) {
        $DOGEBTC = doge.price;
        $DOGE = $BTC / $DOGEBTC;
        $price = parseFloat($DOGE.toPrecision(2));
        // output
        document.getElementById('price').innerHTML = $price;
    });

1 Answers1

9

You absolutely don't want to slow down anything. Your problem is that you're not getting the data in the right order. A simple solution is to make your AJAX requests in serial, but then you are wasting time since you can certainly get both simultaneously.

The best solution to this is to use jQuery's Deferred object along with jQuery.when().

$.when(
  $.getJSON('http://www.cryptocoincharts.info/v2/api/tradingPair/btc_usd'), 
  $.getJSON('http://www.cryptocoincharts.info/v2/api/tradingPair/doge_btc')
).done(function(btc, doge) {
  // This gets called when both URLs have been retrieved.
  $('#price').text((11/btc.price) / doge.price); // Modify as necessary
});

Also, if you need to work with a whole array of Deferreds in the future, see this post: https://stackoverflow.com/a/5627301/362536

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • So do I put my $.getJSON() code into the area that gets called when both urls are retrieved? – David Grzyb Jan 25 '14 at 20:49
  • Wouldn't btc.price and doge.price be undefined here since btc and doge are arrays containing the object? – Jay Jan 25 '14 at 21:29
  • @Jay Possibly, I didn't look at the data coming back. The point here is how to make the requests in parallel, yet wait for them to be done. Hence "modify as necessary" – Brad Jan 25 '14 at 21:37