Nonhlanhla Kunene
Nonhlanhla Kunene

Reputation: 41

jQuery.Deferred exception: Cannot read property '0' of undefined" "TypeError: Cannot read property '0' of undefined

I keep on getting this message on console using codepen:jQuery.Deferred exception: Cannot read property '0' of undefined" "TypeError: Cannot read property '0' of undefined.

My javascript code :

var api_key = "fa15d403d0ab55e3cfd6e0867bbb0114";
$(document).ready(function(){
  var loc;
  //Call the location   
$.getJSON('https://ipinfo.io', function(data){
  loc = data.loc.split(",");
  console.log(loc);
 });
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + loc[0]  +  '&lon=' + loc[1] + '&APPID='+ api_key, function(weather){
         console.table("c ,",weather);
          });
});

Upvotes: 1

Views: 2531

Answers (1)

Krease
Krease

Reputation: 16225

It means you're trying to read the 0 property of an undefined object.

Based on the code you shared, that's happening here: loc[0] - loc is undefined, so it's throwing the error.

The reason it's undefined is because of asynchronous ordering - your first function hasn't executed the callback yet where it's setting loc. Try putting the second call inside the first function (right after your console.log call) instead of after it.

Upvotes: 1

Related Questions