I’m trying to use a callback function to grab the city from one function to be used in the OpenWeatherMap API. Unfortunately, it’s not working. What am I doing wrong?
The getCityWeather(city) call at the bottom throws an error because there’s no city variable in the local scope.
I think you want to call getCityWeather inside the getCity function. Then call getCity at the bottom instead.
The other problem is that codepen blocks HTTP requests (as is the case with the OpenWeather URL). IIRC you need to pay to be able to use their HTTPS version. You have some alternatives here:
Use the Dark Sky API. They support HTTPS out of the box.
Attach https://cors-anywhere.herokuapp.com/ at the beginning of your OpenWeather URL. Note that this is more of a short-term solution.
After all of that it’s only a matter of displaying weather data on your page.
Instead of writing $.getJSON you could instead do the $.ajax({}) command. It’s longer, but you can get around the http/https CORS issues by specifying datatype: jsonp, and it usually gives less problems when compared with the default $.getJSON command.
Also, when you call your function at the end, you just type getCityWeather(). You don’t need to write city inside the brackets.
I ran your code and tried a couple things. There still seems to be a CORS issue with Darksky. It’s an easy fix though. I switched that call from .getJSON() to .get() with the third parameter ‘jsonp’ (I’m not completely clear on the difference… I think declaring it as ‘jsonp’ adds the callback behind the scenes and saves you a step).
The second issue I saw was trying to output the Darksky object directly to html. Instead, I JSON.stringify(ied) the data and sent to .text().