0

May be a silly one , but stuck. This is the code I am trying

<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="javascript" type="text/javascript">
function getWeather() {
  data_Json = {};
  $.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather?q=London",
    dataType: 'JSON',
    success: function(data) {
      //alert(JSON.stringify(data));
      data_Json = data;
      //alert("Weather Report: "+data_Json);
    },
    error: function(e) {
      alert(e.message);
    }
  });
  return data_Json;
}

function temp() {
  //getWeather();
  var obj = JSON.stringify(getWeather());
  //alert("Got"+JSON.stringify(obj));
  //alert(JSON.stringify(getWeather()));
  //document.getElementById("temp").innerHTML = obj.main.temp;
alert("Temp : "+obj);
  }
</script>
</body>
<body>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>

</body>
</html>

It returned {} Not returned the JSON (the return defined in getWeather) Not the temperature (in get element by id part)

The temperature button should return temperature only.

ninja.stop
  • 410
  • 1
  • 10
  • 24
  • Ajax requests are asynchronous (in fact, ajax stands for Asynchronous Javascript and XML). That means that when getWeather() function returns, data_Json is empty (or undefined). The logic you have in your Temp() function should go in the success callback. – Tivie Nov 10 '14 at 19:21
  • then what change you suggest – ninja.stop Nov 10 '14 at 19:35
  • I am not understanding. can you please provide a solution exact where the problem lies? – ninja.stop Nov 10 '14 at 19:37
  • I cannot answer because the question is closed. You can just move the stuff inside temp() function to `success: function(data)` – Tivie Nov 10 '14 at 19:38
  • @Tivie let me know what exactly I have mistaken with example – ninja.stop Nov 10 '14 at 19:39
  • @Tivie which stuff? clearly explain please – ninja.stop Nov 10 '14 at 19:41
  • mate, like I said... I can't ANSWER YOU BECAUSE THE QUESTION WAS CLOSED. Regardless, see this fiddle http://jsfiddle.net/tivie/f78r8o09/ – Tivie Nov 10 '14 at 20:06

0 Answers0