Skip to content
Advertisement

Cant figure out why I cant retrieve data from my API

When I type a city name into my search bar it should pull up information on the weather on that city but I get a 400 bad request error
JAVASCRIPT:

function handleGetData(event){
        event.preventDefault();
        
        const cityName = $("#city").val()
        $.ajax({url: `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=99df413c60279878184277e08a2c6863`})
        .then(
            (data) => {
                console.log(data);
                $("#name").text(data.name)
                $("#temp").text(data.temp)
                $("#feels").text(data.feels_like)
                $("#weather").text(data.weather)
                
            },
            (error) => {
                console.log("bad request: ", error)
            }
            )
            console.log("It's working!")
    }
    $('form').on("submit", handleGetData)

Advertisement

Answer

You are using a promise incorrectly. The correct syntax is .then(result => {}).catch(e => {})

Like this

const cityName = $("#city").val()
$.ajax({url: url})
   .then((data, a, b, c) => {
      console.log(data);
      $("#name").text(data.name)
      $("#temp").text(data.temp)
      $("#feels").text(data.feels_like)
      $("#weather").text(data.weather)
      console.log("It's working!")
   })
   .catch(error => {
      console.error(error) //not necessarily a "bad request"
   })
Advertisement