Search code examples
javascriptajaxethereum

How can I automatically update ethereum price on my website


I want to display the last price of etherum on my website but unfortunately it doesn't update automatically without reloading the page.

<script>
  $.ajax({

    url : 'https://api.coinmarketcap.com/v1/ticker/ethereum/',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {
        eth_price = data[0].price_usd;
        document.getElementById('eth_price').innerHTML = eth_price;
    },
    error : function(request,error)
    {
        console.log('Error by getting the ETH price');
    }
  });
</script>

How can I fix this so the last price is always displayed without reloading the site every time?

I thought ajax is doing that by default?


Solution

  • The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

    setInterval(function(){ 
     $.ajax({
    
        url : 'https://api.coinmarketcap.com/v1/ticker/ethereum/',
        type : 'GET',
        data : {
            'numberOfWords' : 10
        },
        dataType:'json',
        success : function(data) {
            eth_price = data[0].price_usd;
            document.getElementById('eth_price').innerHTML = eth_price;
        },
        error : function(request,error)
        {
            console.log('Error by getting the ETH price');
        }
      })
    }, 3000);