Home > Blockchain >  TypeError when trying to fetch JSON data using jQuery
TypeError when trying to fetch JSON data using jQuery

Time:10-28

So I'm trying to fetch JSON data from this link https://covid.ourworldindata.org/data/owid-covid-data.json using this code

$.ajax({
  type: "GET",
  url: "https://covid.ourworldindata.org/data/owid-covid-data.json/",
  success: function (data) {
    $("h5").each(function () {
      var code = $(this).data("code"); // atribut data-code
      $(this).html(data[code]["location"]);
    });
  },
});

It's working fine and the tag is also set to the value I wanted to, but when I check the console I got this error

Uncaught TypeError: Cannot read properties of undefined (reading 'location')

and it points to this line

$(this).html(data[code]["location"]);

how fix that?

CodePudding user response:

Whatever is contained in the code variable doesn't exist in the data object, which means it returns undefined. And then you're trying to call the location property on undefined which doesn't exist so it returns an error. You can prevent it with an early return:

var code = $(this).data("code");
if (!data[code]) return;
$(this).html(data[code]["location"]);

Or if you need to add something to those elements no matter if it exists or not you could instead do something like:

var code = $(this).data("code");
if (!data[code]) {
  $(this).html('Value does not exist');
  return;
};
$(this).html(data[code]["location"]);

CodePudding user response:

My guess is that you have some <h5> elements that do not have a code dataset property so you're essentially trying to use

data[undefined].location

which will never work.

Make sure you're only looking at the elements with the appropriate data

$.getJSON("https://covid.ourworldindata.org/data/owid-covid-data.json")
  .done(data => {
    $("h5[data-code]").each((_, h5) => {
      $(h5).html(data[h5.dataset.code]?.location)
    })
  })
  • Related