0

I am trying to create ajax calls using information from countries but when I run the program it sends me the next error:"Uncaught TypeError: Cannot read properties of undefined (reading 'name') at XMLHttpRequest. (script.js:25)"

My Javascript code is the next one:

const request = new XMLHttpRequest();

request.open('GET', 'https://restcountries.com/v3.1/name/taiwan')
request.send();

request.addEventListener('load', function(){
  // console.log(this.responseText)
  const [data] = JSON.parse(this.responseText)
  console.log(data);

  const html= `<article class="country">
    <img class="country__img" src="${data.flags.svg}" />
    <div class="country__data">
      <h3 class="country__name">${data.name.common}</h3>
      <h4 class="country__region">${data.region}</h4>
      <p class="country__row"><span></span>${(+data.population/1000000).toFixed(1)}</p>
      <p class="country__row"><span>️</span>${data.languages[0]}</p>
      <p class="country__row"><span></span>${data.currencies[0].name}</p>
    </div>
  </article>`;

  countriesContainer.insertAdjacentHTML('beforeend', html)
  countriesContainer.style.opacity = 1;
});
Albert Rmz
  • 33
  • 2
  • 2
    Please add console.log(data) – Huy Nguyen Nov 09 '21 at 07:45
  • `currencies[0].name` won't work, `currenies[0]` is an object with a key of `TWD`, it doesn't have a `0` key – Nick Parsons Nov 09 '21 at 07:52
  • yes, do you know how could it work without writing the TWD (currencies.TWD.name). Sorry I am new into this. My idea is then wrapped into a function and then call the function with different country name so then can show the information of any country without changing every time to every specific currency. – Albert Rmz Nov 09 '21 at 07:56
  • @AlbertRmz In the link provided at the top of your question you'll see the heading **"Preliminaries"**, which under that you'll see a part about *bracket notation*. You can use that idea `currencies[countryName].name` – Nick Parsons Nov 09 '21 at 08:03

0 Answers0