1

I am making a simple weather app with JavaScipt. My goal is when the user types in a location and the weather provider doesn't have that location, then the input box shakes (which is what loadWeatherError() does). The code below is running the else statement twice and then running the if code. This means that the loadWeatherError() function is being run twice and the input box shakes even if the location is valid. So when I run it I get the Error 2 alert twice then the Error 1 alert once. Is there a way that would only make the loadWeatherError() function only run once and run only if the weather provider didn't return the correct data?

xhr.onreadystatechange = function() {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK)
      alert("Error 1");
    var data = JSON.parse(xhr.responseText);
    if (data.response) { //deal with wunderground api

    } else { //deal with Yahoo api

    }
  } else {
    alert("Error 2");
    loadWeatherError();
    options.error("There is a problem receiving the latest weather. Try again.");
  }

};
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • 1
    Have you console logged the readyState to see what it's value(s) were? I'm a little confused why you consider states 0-3 as errors. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState – Taplar May 29 '17 at 16:08
  • Unless your issue is with your inner OK check not using {} so that that else is paired with it instead. – Taplar May 29 '17 at 16:11
  • I don't consider states 0-3 as errors. I believe what is happening is every time the state changes the function runs and since it's not at state 4 the else code runs. Then it reaches the next state and the else code runs again until it reaches state 4. However, I don't see how this would happen based on this code. – Limited Access May 29 '17 at 16:14

1 Answers1

2

What is happening is your state is changing, but it is not equaling 4. You have to go through each of the ready states in order to reach a DONE value. Your code is running each time the state changes, which is what causes the error. Remove the code that outputs the error if the state is not correct:

xhr.onreadystatechange = function() {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) {
      alert("Error 1");
    } else {
      alert("Error 2");
      loadWeatherError();
      options.error("There is a problem receiving the latest weather. Try again.");
    }
    var data = JSON.parse(xhr.responseText);
    if (data.response) { //deal with wunderground api

    } else { //deal with Yahoo api
      alert("Error 2");
      loadWeatherError();
      options.error("There is a problem receiving the latest weather. Try again.");
    }
  }
};
Sam Worrod
  • 33
  • 6