I tried to get the weather from an API on a specific location by getting the value form an input but that gives me the 400 error. It works only if I hardcode the location name in the URL, but that is not the functionality I’m looking for. I need it to be dynamically changed as the input.value is entered. Is there a better approach to it?
let input = document.getElementById('input')
let searchButton = document.getElementById('button')
let showInfo = document.getElementsByClassName('conteinerInfo')
showInfo[0].setAttribute('id', 'mainddiv')
let divId = document.getElementById('mainddiv')
function getWeather () {
fetch(`http://api.weatherapi.com/v1/current.json?key=XXXXXXXXXXXXXXXXXX&q=${input.value}&aqi=no`)
.then(response => response.json())
.then(res => {
searchButton.addEventListener('click', ()=> {
divId.innerHTML = 'Temp' + ' ' + res.current.temp_c + "" + 'C'
})
})
}
getWeather()
>Solution :
This makes very little sense:
function getWeather () {
fetch(`http://api.weatherapi.com/v1/current.json?key=XXXXXXXXXXXXXXXXXX&q=${input.value}&aqi=no`)
.then(response => response.json())
.then(res => {
searchButton.addEventListener('click', ()=> {
divId.innerHTML = 'Temp' + ' ' + res.current.temp_c + "" + 'C'
})
})
}
getWeather()
What the code essentially says is:
- Make an API request immediately when the page loads, using whatever default value is in the input.
- After receiving a response from the API, create a click handler which will display that response to the user when they click the "search" button.
I suspect you intended to perform the API request after the user clicks the search button? In which case you’d create a click handler which does exactly that… performs the API request and displays the result. For example:
function getWeather () {
fetch(`http://api.weatherapi.com/v1/current.json?key=XXXXXXXXXXXXXXXXXX&q=${input.value}&aqi=no`)
.then(response => response.json())
.then(res => {
divId.innerHTML = 'Temp' + ' ' + res.current.temp_c + "" + 'C'
})
}
searchButton.addEventListener('click', getWeather)