El-Cortez El-Cortez - 2 months ago 16
Javascript Question

Very simple API call that doesn't return anything

I'm trying to get data from the open weather API but all I get is an object that I cannot use (the JSON is inside but I cannot access it)

I've read a lot about asynchronous JS and callbacks. I'm really not sure whether I need a callback for EACH API i'm using, I already used one to get latitude and longitude but now, for the open weather API, i need to pass these lat and lon as parameters for the API call, and I have no idea on how to do that if I use callbacks (as it seems that arguments in callbacks functions are not the ones used in the function but the ones that actually get returned, which I find extremely confusing).

Can anyone tell me what I'm doing wrong here?

$(document).ready(function() {
$('#getWeather').on('click', function(){
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
console.log(myWeather(lat, lon));
// Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
});
})
})

function myLatAndLon(callback) {
$.getJSON('http://ip-api.com/json/').done( function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}

function myWeather(lat, lon) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
// The params are good, and when I type them on my browser, everything works fine
}


EDIT : I'm adding a picture to make it clearer what I'm trying to do and what I get eventually

Answer

Change your code to it and test again :

$(document).ready(function() {
  $('#get').on('click', function() {
    myLatAndLon(function(result) {
      var lat = result[0];
      var lon = result[1];
      alert(JSON.stringify(result));
      $req = myWeather(lat, lon);
      $req.done(function(R) {
        alert(JSON.stringify(R))
      });
    });
  })
})

function myLatAndLon(callback) {
  $.getJSON('//ip-api.com/json/').done(function(location) {
    var arr = [];
    arr.push(location.lat);
    arr.push(location.lon);
    callback(arr);
  });
}

function myWeather(lat, lon) {
  return $.getJSON('//api.openweathermap.org/data/2.5/weather', {
    lat: lat,
    lon: lon,
    APPID: 'a9c241803382387694efa243346ec4d7'
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">get</button>

And also you should check your server for CORS limitations read more here: http://enable-cors.org/server.html