Search code examples
javascriptjqueryjsonweather-api

JSON not firing API Key for Weather App


I'm doing FCC weather app project using the Open WeatherMap API. I saw chrome is making issues serving geolocation over HTTP so I decided to use a user input for zip code instead.

$(document).ready(function(){

  // var zipCode = "54901";
  var key = "id=524901&APPID=24d9e7758a30704bbc766831845bcb5f";

  $(".btn").on("click", function(){
    var zipCode = document.getElementById("zipCode").value

    var api = "api.openweathermap.org/data/2.5/weather?zip=" + zipCode + ",us" + "&" + key;  
    console.log("Before JSON"); //Works
    console.log(api); //Copy & Paste into browser works
    $.getJSON(api, function(data){
      console.log("JSON fired"); //Doesn't Log

    });  
  });  
});

HTML

<div>
  <h1>Weather App</h1>
  <input id="zipCode" type="text" placeholder="53154" />
  <button class="btn btn-primary" type="submit">Submit</button>
</div>

User input gives a valid zipCode and everything works until my request for the JSON. Is this because my api isn't being concatenated correctly?

My codepen: https://codepen.io/dylanmparks/pen/LyRyOP?editors=1011


Solution

  • $(document).ready(function(){
    
      // var zipCode = "54901";
      var key = "id=524901&APPID=24d9e7758a30704bbc766831845bcb5f";
      
      $(".btn").on("click", function(){
        var zipCode = document.getElementById("zipCode").value
      
        var api = "http://api.openweathermap.org/data/2.5/weather?zip=" + zipCode + ",us" + "&" + key;  
        console.log("Before JSON"); //Works
        console.log(api); //Copy & Paste into browser works
        $.getJSON(api, function(data){
          console.log("JSON fired => ", data); //Doesn't Log
        }).fail(function(jqxhr, textStatus, error){
          console.log('Error:', textStatus, error)
        });  
      });  
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
      <h1>Weather App</h1>
      <input id="zipCode" type="text" placeholder="94040" />
      <button class="btn btn-primary" type="submit">Submit</button>
    </div>