Unable use getJSON() to get data from OpenWeatherMap API

Unable use getJSON() to get data from OpenWeatherMap API
0.0 0

#1

I am currently building “Local Weather” project, and I can not fetch() data from API.
+I use OpenWeatherMap api, which is fine when it pastes this link to the browser: api.openweathermap.org/data/2.5/weather?q=Montreal,ca&units=imperial&appid=0e6024b5a3e856bcfcca5712554daef3
+I try to getJSON() it, with a error handler, I caught the error of which It fails to get data from the url. Why ? Which steps I have taken wrong:
+Full code
const weatherURL=“api.openweathermap.org/data/2.5/weather?q=Montreal,ca&units=imperial&appid=0e6024b5a3e856bcfcca5712554daef3”;
$.getJSON(weatherURL, function(json){
console.log(json.coord.lon);
alert(‘aa’);
}).fail(function() {
console.log( “error fetching data” );
})
});


#2

Hi Andrew

I have managed to get your code to run in chrome dev console by adding https to the url, it returns the json as expected for me. You should be able to copy/paste and try it in the browser console.

// load jquery in browser console
// see: https://gist.github.com/kkarimi/55d2538b8f4c474dba1d
(function() {
  if (! window.jQuery ) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js'; // you can change this url by latest jQuery version
    (document.getElementsByTagName('head')[0] ||
      document.getElementsByTagName('body')[0]).appendChild(s);
  }
}());

// your code below
// removed '});' at end an changed all quotations marks to single quotes
// added 'https://' to url

const weatherURL = 'https://api.openweathermap.org/data/2.5/weather?q=Montreal,ca&units=imperial&appid=0e6024b5a3e856bcfcca5712554daef3';
$.getJSON(weatherURL, function(json){
console.log(json.coord.lon);
alert('aa');
}).fail(function() {
console.log( 'error fetching data' );
});

Hope that helps