Connecting to External Sites

When dealing with AJAX in JavaScript, you can connect to a wide range of free APIs to pull in data. In the previous chapter, you used foursquare to connect to local places. In this example, you will use the Twitter API to search for mentions of the wine that you are looking for and display the results below the wine details.

Building the template

Because Twitter’s data is returned in JSON, you can use Handlebars to help build the HTML template that each tweet will display. If you followed the steps previously for the activity feed, you should have added HandlebarsJS to your project already, otherwise you can refer back to get it set up within your project.

1. Define your template structure. To use Handlebars, you must create a template in a script tag with the desired HTML. Add this code before the closing </body> tag in index.html:

<script id=”social-template” type=”text/x-handlebars-template”>

....

</script>

When you compile your template, Handlebars takes the contents of this script file and combines it with the JSON object to produce the desired result.

2. Build the script to pull in the tweets based on the wine name. Add this script right after you insert the wine data into the detail element.

$(“#detail”).html(code);

$.getJSON(“http://search.twitter.com/search.json?q=”+res.rows.item(0).wine_name, function(data) {

console.log(data);

});

As of March 15, 2013, Twitter will be rolling out a new version of their API that requires all API requests ...

Get Smashing Mobile Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.