Exercise - jQuery AJAX

Photo Handling

by Ryan Morris

HTML

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<div class="container">
  <h2>Photos</h2>

  <div id="album">
    <p>We want our photos to show up here.</p>
  </div>
</div>

<script id="photo-template" type="text/x-handlebars-template">
  <div class="entry">
    <h6>{{title}}</h6>
    <img src="{{thumbnailUrl}}" alt="{{id}}" />
  </div>
</script>

CSS

#album img {
  width: 20px;
  height: 20px;
}

JavaScript

// Ajax with jQuery
// We will be using this service to fetch data
// This server is friendly enough to be CORS:*
//     http://jsonplaceholder.typicode.com/
// if we have trouble with that, we can do this on
// local servers fetching up static .json data
//

// Write an ajax request to fetch photo data
// Rendering images to the page
// 
// Then set up a basic photo template using handlebars


$.ajax({
  url: 'http://jsonplaceholder.typicode.com/photos',
  data: {
    albumId: 10
  },
  dataType: 'json'
}).then(function(response) {

});


/* Solution






var photoTemplate = Handlebars.compile($("#photo-template").html());

function handleResponse(response) {

  var $album = $("#album");

  // for each array item

  response.forEach(function(item) {

    // render an album item

    //var newImg = "<img ";
    //newImg += "src='" + item.thumbnailUrl + "' ";
    //newImg += " />";

    var newImg = photoTemplate(item);

    $album.append(newImg);


  });
}

$.ajax({
  url: 'http://jsonplaceholder.typicode.com/photos',
  data: {
    albumId: 10
  },
  success: handleResponse,
  dataType: 'json'
});

/**/