Fun with the Twitter API
Just a few different examples of leveraging the Twitter API using JSONP to get around cross origin request sharing.
HTML
<!DOCTYPE>
<html>
<head>
<title>base64 test</title>
</head>
<body>
<fieldset id="controls-each">
<legend>Controls for Each</legend>
<label>get Tweets</label><button id="btn-getTweets" data-action="getTweets">Get for Tweets</button><br />
<label>get Friends</label><button id="btn-getFriends" data-action="getFriends">Get for Friends</button><br />
<label>get Follows</label><button id="btn-getFollows" data-action="getFollows">Get Follows</button><br />
</fieldset>
<div id="controls-all">
<legend>Controls for All</legend>
<label>get All</label><button id="btn-getAll" data-action="getAll">Chain all Gets</button><br />
</div>
<div id="inTweets">
<span>Dean Tweets</span>
<input type="hidden" id="twitterUsername" name="twitterUsername" value="deanpeters" />
</div>
<div id="outTweets"></div>
</body>
</html>
CSS
li { margin: 10px 0; }
JavaScript
var listStatus = function() {
var twitterUsername = $("#ceryni17").val();
var url = "http://twitter.com/status/user_timeline/" + twitterUsername + ".json?count=5&callback=?";
$.getJSON(url, function(data) {
var twitterList = $("<ul />");
$.each(data, function(index, item) {
$("<li />", {
"text": item.text
}).appendTo(twitterList);
});
console.log(twitterList);
$("#outTweets").fadeOut("fast", function() {
$(this).empty().append(twitterList).fadeIn("slow");
});
});
}
listStatus();
$("body").delegate("button", "click", function(obj) {
var targetAction = obj.target.dataset.action + "()";
console.log(targetAction);
eval(targetAction);
});
// $.when(getTweets(), getFriends(), getFollows()).then(function(){
//apply templates
//});
// http://net.tutsplus.com/tutorials/javascript-ajax/fun-with-jquery-templating-and-ajax/
$.ajaxSetup({
dataType: "jsonp"
});
var getAll = function() {
$.when(getTweets(), getFriends(), getFollows()).then(function() {
console.log("chain of get events complete");
});
}
var getTweets = function() {
$.ajax("http://api.twitter.com/statuses/user_timeline/ceryni17.json", {
async: true,
success: function(data) {
var arr = [];
for (var x = 0; x < 5; x++) {
var dataItem = {};
dataItem["tweetlink"] = data[x].id_str;
dataItem["timestamp"] = convertDate(data, x);
dataItem["text"] = breakTweet(data, x);
arr.push(dataItem);
}
tweetData = arr;
console.log("getTweets:");
console.log(tweetData);
}
});
}
var getFriends = function() {
return $.ajax("http://api.twitter.com/1/statuses/friends/ceryni17.json", {
dataType: "jsonp",
async: true,
success: function(data) {
var arr = [];
...