I am trying to make a website that shows the weather forecast. It already shows the weather forecast. If I want to enter a city that doesn't exist I want a message to appear. I already tried something with 404 but it doesn't show up in the console log. I hope someone can help me. Thank you in advance!

function getData() {

    let apikey = 'private';
    var city = document.querySelector('#city').value;
    let requestURL = 'https://api.openweathermap.org/data/2.5/forecast?q='+city+'&appid='+apikey+'&units=metric';
    let request = new XMLHttpRequest();
    request.open('GET', requestURL, true);
    request.responseType = 'json';
    request.send();
    request.onload = function () {
        let data = request.response;
        addData(data);
        var body = document.querySelector('body');

        var div = document.createElement('div');

        for (var i = 0; i < data.list.length; i += 8) {
            // console.log(data.list[i].dt_txt);
            div.appendChild( createEL('p',
                '<b>Date en time: ' + data.list[i].dt_txt+'<br></b>'+
                'City: ' + city+'<br>'+
                'Country: ' + data.city.country + '<br>'+
                'Temperature: ' +data.list[i].main.temp+'<br>'+
                'Weather: ' +data.list[i].weather[0].main));

        }

        if (XMLHttpRequest == '404'){
            console.log("Doesn't exist")
        }


        var body = document.querySelector('body');
        body.appendChild(div);

        function createEL(tag, content){
            var el = document.createElement(tag);
            el.innerHTML = content;
            return el;
        }
    }
}

var button = document.querySelector('#show');

button.addEventListener("click", function (ev) {
    ev.preventDefault();
    getData();
},false);

function addData(jsonData) {

    var city = document.querySelector('#city').value;

    var input = document.querySelector('#city');



}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Weather</title>
</head>
<body>
<h1>Weather</h1>

City: <input type="text" id="city" name="city" placeholder="city">
<button id="show" name="show">Show</button>

<script src="js/weather.js"></script>
</body>
</html>

2 Answers

1
Quentin On

XMLHttpRequest will never be equal to 404. It is the constructor function you used to created the object that made the HTTP request!

You need to examine request.status.

0
DMishra On

You need to check request.status if you are sending status code from API.

let request = new XMLHttpRequest()
console.log(request.status);

To display does not exist you can check the response data length like

if(data.list.length==0)
{
    console.log("Does not exists.");
}