0

I am getting an error while trying to access the string AFH(currencyId). The error I am getting is "Uncaught TypeError: Cannot read property 'Continents' of undefined" JSON

Here is how I am trying to access the string.

(1) After I made ajax request to the endpoint of the Json file, I stored the info(data) under variable named data when the ajax request is success.

(2) This is where the error comes from:

console.log(data.Continents[0].Countries[0].CurrencyId)

Can anyone help me understand what I am missing?

3 Answers3

2

You have a space between Countries and [0]

console.log(data.Continents[0].Countries [0].CurrencyId)

should be

console.log(data.Continents[0].Countries[0].CurrencyId)
Matt Busche
  • 14,216
  • 5
  • 36
  • 61
1

The most likely culprit is the A of AJAX. Assuming that your code looks something like this (using jQuery for brevity):

var data;
$.get('/endpoint.json', function(response) {
  data = response;
});
console.log(data.Continents[0].Countries[0].CurrencyId);

In this simple example, the data variable is being defined but only after the AJAX request completes however because the AJAX request is made asynchronously, the console.log() is executed immediately (before the data variable is actually defined). This can seem counter intuitive because by the time you move the cursor down to the JS Console the data variable will have been defined and then can be logged. The obvious solution to this issue is to move your console.log inside your success callback or define a separate function that uses your data and call it from the ajax success callback.

Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
  • it turns out that the url does not have .json extension. Does that make a difference to how I should approach the problem? –  May 03 '17 at 01:18
  • There can be a related issue that jQuery can hide. If the server is not expressly sending a `content-type` header with the value `application/json`(http://stackoverflow.com/a/477819/16959) then jQuery will look at the URL to guess if the result should be parsed as JSON. You can override this by passing a datatype to `jQuery.get()` (https://api.jquery.com/jquery.get/) or by parsing the response with vanilla JavaScript using `JSON.parse(data)` however this would not explain your `undefined` `data` issue as in that case `data` would be a `String` (though still lacking a `Continents` property) – Jason Sperske May 03 '17 at 17:59
  • Finally, you are on the right track when it comes to the error I am getting –  May 05 '17 at 02:42
0

You need to post more of the code. Sure console.log(data.Continents[0].Countries[0].CurrencyId) might be throwing the actual error, but it is most likely because previous lines are not doing what they're supposed to. Most likely your code to do the ajax request isn't functioning properly, so data isn't actually being filled with the JSON and is being left as undefined which would throw that error.

Francesco
  • 99
  • 1