XHR Example

Grabs weather from yahoo and outputs it.

by jordwms

HTML

<table id="weather">
    <thead>
        <tr>
            <th id="header" colspan="2">Conditions</th>
        </tr>
    </thead>
</table>

<label for="zip">Zip Code</label>
<input type="text" name="zip" id="zipInput"></input>
<button id="zipButton">Click here for weather in your Zip Code</button>

CSS

table {
    width: 300px;
    border-spacing: 0;
    border-collapse: collapse;
}
th {
    width: 25%;
    border-bottom: 1px solid gray;
}
td {
    width: 75%;
    border-bottom: 1px solid gray;
    border-left: 1px solid gray;
    padding-left: 5px;
}

JavaScript

//var url = "https://query.yahooapis.com/v1/public/yql?q=SELECT+item.condition%2citem.title+FROM+weather.forecast+WHERE+woeid%3d56574477&format=json";
var url = "";
document.getElementById('zipButton').addEventListener('click',function onZipButtonClick() {
 	var zipVal = $("#zipInput").val();   
    url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+zipVal+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

    xhr.open('GET', url, true);
    xhr.send();
});


var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.addEventListener('load', function (e) {

    var tbody, data, output = '';

    if (xhr.status == 200) {

        //turn the response into a json object
        data = JSON.parse(xhr.responseText);
        
        // update the header row
        document.getElementById('header').innerHTML = data.query.results.channel.item.title;
        
        // grab just the conditions node
        conditions = data.query.results.channel.item.condition;

        //format the output in a table body
        for (var key in conditions) {
            output += '<tr>';
            output += '<th>' + key + '</th><td>' + conditions[key] + '</td>';
            output += '</tr>';
        }

        output += '</tbody>';
        tbody = document.createElement('tbody');
        tbody.innerHTML = output;

        document.getElementById('weather').appendChild(tbody);

    }
});
xhr.send();