I am trying to get BTC current price from the following API endpoint:
function CoinbaseBTCPrice(){
$.ajax({
url: "https://api.coindesk.com/v1/bpi/currentprice.json",
success: function(bitcoinPrice){
console.log(bitcoinPrice.bpi.USD.rate)
}
})
}
When I try to do this it says that the data I am looking for is undefined.
You need to parse the returned JSON string first using JSON.parse
. Find out more in here.
CoinbaseBTCPrice();
function CoinbaseBTCPrice(){
$.ajax({
url: "https://api.coindesk.com/v1/bpi/currentprice.json",
success: function(bitcoinPrice){
console.log(JSON.parse(bitcoinPrice).bpi.USD.rate)
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For shorter version, you can you $.getJSON
instead.
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(currentPriceInfo){
console.log(currentPriceInfo.bpi.USD.rate)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>