Home > Back-end >  Calling API with Javascript html
Calling API with Javascript html

Time:03-31

What is the correct way to call this API? The api url is: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd

I tried with this code

<p id="demo">
 </p>
 <script>
  var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.bitcoin;
        }
    };
    xmlhttp.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"   new Date().getTime(), true);
    xmlhttp.send();
 </script>

however the value I get is [object Object]. I want to get the value in "usd".

Where am I wrong? Thx

Replaces myObj with myObj.usd but returns null value

CodePudding user response:

The API returns in the form of {"bitcoin":{"usd": -insert value here-}}, so you have to use myObj.bitcoin.usd

CodePudding user response:

You need to access the usd part of the object when you set the innerHTML as @SuspenseFallback mentioned.

You also need to remove the new Date().getTime() part from your URL string. I don't see a date part in the API docs for the price endpoint.

CodePudding user response:

you should use the fetch method. the better and the modern way of calling API using native javascript.

There is no problem with the way you did it but there are a few things that you can do with fetch and not with XHR.

you can read more about fetch by this link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

there is an example of using fetch:

fetch(
  "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
)
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });

or you can use async-await to achieve the same result :

(async () => {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
  );
  const data = await response.json();
  console.log(data);
})();

note: I have used Javascript Self Invoking Functions which is a function that calls itself.

  • Related