Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Calling API with Javascript html

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!