brianrhea
brianrhea

Reputation: 3724

Able to get JSON data, but not showing up in Handlebars template

I have the following in my page, ready to:

<div id="result"></div>
<script id="some-template" type="text/x-handlebars-template">
  <table>
    <thead>
      <th>Name</th>
    </thead>
    <tbody>
      {{#athletes}}
        <tr>
          <td>{{firstName}} {{lastName}}</td>
        </tr>
      {{/athletes}}
    </tbody>
  </table>
</script>

and the following JavaScript firing below:

var source   = $("#some-template").html();
var template = Handlebars.compile(source);

var data = $.getJSON("http://api.espn.com/v1/sports/baseball/mlb/athletes?apikey=axfy7dvwqzktu28srdjna8ta", function() {
  alert('Load was performed.');          
});

$("#result").html(template(data));

I get an alert that the load was performed and I can see all the data in Firebug, but the #result div does not display the data.

If I replace var data with straight text as below it all functions exactly right:

var data = { athletes: [
    {firstName: "Josh", lastName: "Hamilton"},
    {firstName: "Yu", lastName: "Darvish"},
    {firstName: "Ian", lastName: "Kinsler"}
  ] }

The "athletes" key is a couple layers down in the JSON tree (sports -> leagues -> athletes). What am I not understanding about how to extract this data from the API result?

Upvotes: 0

Views: 2820

Answers (3)

eon
eon

Reputation: 1938

If for some reason you're can't change your $.get() to $.getJSON(), you'll have to JSON.parse(theData) in your success callback or the template will have no data to render. (Obvious now, but took me a moment when I had that situation.)

Upvotes: 0

Rajat
Rajat

Reputation: 34108

Try something like this:

$.getJSON("http://api.espn.com/v1/sports/baseball/mlb/athletes?apikey=axfy7dvwqzktu28srdjna8ta", function(data) {
      alert('Load was performed.');
      $("#result").html(template(data.sports[0].leagues[0].athletes));          
});

Also, an important sidenote: You have pasted your apikey. I think you would like to keep that private.

Upvotes: 0

Chris Johnson
Chris Johnson

Reputation: 21

You're using $.getJSON wrong. It doesn't return the data, but rather calls the success function (where you're alerting I believe) and passes the data to that. Move your html population into the success callback.

It does this because AJAX requests are asynchronous in nature by default

Upvotes: 1

Related Questions