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

150
Views
Javascript is not accepting JSON data as variable

I am trying to connect to an API to display some data on my website.

I've already defined Http as new XMLHttpRequest();, and url as the API endpoint.

Here's the code:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.stringify(Http.responseText)
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

However, when I run the code, I get the following error:

Uncaught TypeError: api.total_bandwidth is undefined

What is wrong here? Is Http.responseText already an Object? Did I define the API wrong?

This is the response of api:

{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're stringifying the object (response), then trying to get "TB" from a string.

Try parsing api then getting the properties from it:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
    var api = JSON.stringify(Http.responseText);
    var apiJson = JSON.parse(api);
    document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};

Edit: Turns out that "JSON.stringify" was actually a mistake.

I think you meant to use JSON.parse rather than JSON.stringify... - Robin Zigmond

I think you meant JSON.parse (to PARSE the response text) instead of JSON.stringify:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.parse(Http.responseText);
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

Learn more about JSON.parse at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

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!