Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Failed to load resource: the server responded with a status of 400 (Bad Request) solution?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Make an API request immediately when the page loads, using whatever default value is in the input.
  2. 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading