Skip to content

Asynchronous External Content

JP Barbosa edited this page Jan 21, 2016 · 3 revisions

Asynchronous External Content

Create placeholder in the view
nano app/views/layouts/application.html.erb
...
    <div id="navbar">
      <ul class="nav navbar-nav">
        <%= link_to('Rails Apz', '/', class: 'navbar-brand') %>
        <li><%= link_to('Articles', articles_path) %></li>
        <li><%= link_to('Authors', authors_path) %></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <p id="weather" class="navbar-text">Loading weather...</p>
      </ul>
    </div>
...
Get Open Weather API access
open http://openweathermap.org/appid#get
Add data using JS
nano app/assets/javascripts/application.js
...
ready = function() {
  ...
  weather();
}
$(document).ready(ready);
$(document).on('page:load', ready);
function weather() {
  url = 'http://api.openweathermap.org/data/2.5/weather?q=Sao_Paulo,br&units=metric&APPID=YOUR_API_ID'
  $.getJSON(url, function(data) {
    $('#weather').html('Sao Paulo: ' + data.main.temp + ' Celsius');
  });
}
Open any page in the browser and check for weather info
open http://localhost:3000
Add asynchronous external content to Git
git add .
git commit -m "Add asynchronous external content"