jQuery Ajax Example

by Ryan Morris

HTML

<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<table>
  <thead>
  <tr>
  <td>Date</td><td>High</td><td>Low</td>
  </tr>
<tbody>
  
</tbody>
</table>

CSS

table{
  font-family:arial;
  font-size:1em;
  color:#999;
}

table thead{
  color:#000;
}

table td{
  padding:2px;
}

tbody td{
  background-color:#ececec;
}

JavaScript

$().ready(function() {

  var myKey = '94073822fd61f918',
  	$table = $("table"),
  	req;
    
  req = $.ajax({
  	url: 'https://api.wunderground.com/api/' + myKey + '/forecast10day/q/CA/San_Francisco.json',
    method: 'GET'
  });
  
  req.done(function(response) {
    
    // check out the console to inspect the data returned
    console.log(response);
    
    // we could create and append a row in the iteration
    // but we combine rows into a single string 
    // for a more performant DOM manipulation later
    var rows = '';
    
    $.each(response.forecast.simpleforecast.forecastday, function(i, val) {
     
     rows += "<tr>";
     rows += "<td>" + val.date.monthname + ' ' + val.date.day + "</td>";
     rows += "<td>" + val.high.celsius + "℃</td>";
     rows += "<td>" + val.low.celsius + "℃</td>";
     rows += "</tr>";
     
    });
    
    $("tbody", $table).append(rows);
    
  });
  
  // to test this, just change the API Key to be invalid
  req.fail(function(req, status, error) {
  
  	console.log("There was an error in the request:", error);
  
  });

});