Search code examples
javascriptjqueryobjectif-statementgetjson

If state check for object property that is not always there breaks the function


I am building a weather app. The user submits a zip code or city name + state and off the $.getJSON function goes.

The function I am trying to implement is to check if the user gave a bad value. For example, if the user inputs New York, New York, Baltimore or 90210 then the user will get the forecast. However, if the user inputs something wrong like 999999999 that cannot be found, then the user should be alerted and the function should reset the input for the user to try again.

I thought that if statements didn't always need an else which would allow me to get by. The problem is that for a properly formatted request, data.response.error.description does not exist so the function gets hung up and quits. How can I get around if this object property does not exist? I tried with some else statements but that only seemed to check for data.response.error.description to equal something else.

What am I doing wrong?

var url = 'http://api.wunderground.com/api/7434225907cbf087/forecast/q/';
var userInput;
var end = '.json';
$(document).ready(function() {
  $('#button').on('click', function() {
    $('#myDiv').html("");
    userInput = ($('#input').val());
    $.getJSON(url + userInput + end, function(data) {
      console.log("user input: " + userInput);
      console.log(data);
      if (data.response.error.description ==
        "No cities match your search query") {
        $('#input').val("");
        alert("Your input was incorrect, try again!");
        return;
      };

      $('#userSubmission').html("");
      $('#userSubmission').html(userInput);
      //var highFahrenheit = data.forecast.simpleforecast.forecastday[0].high.fahrenheit;
      //console.log(data.forecast.simpleforecast.forecastday[0])
      //console.log(highFahrenheit);
      $('#myDiv').html("Today's high is " + highFahrenheit +
        " degrees Fahrenheit");
    });
    $('#input').val("");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click Me</button>
<input type="text" placeholder="Location" id="input">
<div id="userSubmission"></div>
<div id="myDiv"></div>
<div id="verify"></div>


Solution

  • Before you check for a sub-property, check that the containing property exists:

    if (data.response && data.response.error && data.response.error.description == "No cities match your search query")