Newbie question: How do i put *this* variable into* there*? (use current location for weather widget)

I’m often on a different topic of forum answering questions (sometimes really really basic questions from newbies), but on the I am the newbie when it comes to web design, and sometimes the most basic questions are hard to answer via Google, when you’re so new, ya don’t know what the heck you’re even asking… I’m sure this is one of those times. :slight_smile:

I have a weather widget and I want it to grab the user’s current location data (based on IP) from a json URL.

As I understand it, this will populate [response] with the current user’s location info, including [response.latitude], [response.longitude] & [response.city]:

<script>
function getLocation {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://freegeoip.net/json/", false);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
}
</script>

…and this will display a nice weather widget based on provided location:

<iframe id="forecast_embed" type="text/html" frameborder="0" height="220"
width="50%"
src="http://forecast.io/embed/#lat=33.8136&lon=-117.9197&name=Disneyland&color=#00aaff&font=Georgia&units=si">
</iframe>

So, how do I refer to the variable so the iframe src is:

#lat=[response.latitude]&lon=[response.longitude]&name=[response.city]

?

Thanks!

Hi,

You could use onreadystatechange to deal with the response from the server and set it in there. Something like this:

function getLocation {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "http://freegeoip.net/json/", false);
  xhttp.setRequestHeader("Content-type", "application/json");

  xhttp.onreadystatechange = function () {
    if(xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
      // xhttp.responseText contains the response
      // You can now get a reference to the iframe and manipulate it's src attribute
    }
  };

  xhttp.send();
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.