I'm having a really difficult time finding a way to embed a tweet into a web page dynamically. Ideally, I'd like to have a user enter a Twitter status URL (like https://twitter.com/robdelaney/status/329651129988288514), click a button, and have the tweet embed in a div.
Here's what I've got so far:
$(document).ready(function(){
$("#resolve").click(function(){
var url = $("#retweet_form_url").val();
if (url==""){
$(".controls").addClass("error");
}
else {
$("#tweet_div").show();
$.ajax({
url: "https://api.twitter.com/1/statuses/oembed.json?url="+url,
dataType: "jsonp",
success: function(data){
// Derp! What do I do here?
}
});
}
})
})
When I test this with a URL I do get a JSON response back from Twitter than includes the entire HTML needed to embed the tweet, but when I try to parse it I can't get anything to appear in my div. Can anyone point me in the right direction?
data
is an object containing the tweet details, including an html
member containing the actual embed code. So:
// ...
success: function(data){
$("#tweet_div").html(data.html);
}
// ...
$(document).ready(function() {
$("#resolve").click(function() {
var url = $("#retweet_form_url").val();
if (url == "") {
$(".controls").addClass("error");
} else {
$("#tweet_div").show();
$.ajax({
url: "https://api.twitter.com/1/statuses/oembed.json?url=" + url,
dataType: "jsonp",
success: function(data) {
$('#tweet_details').html(data.html);
}
});
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=retweet_form_url value="https://twitter.com/robdelaney/status/329651129988288514" />
<button id=resolve>resolve</button>
<div id=tweet_details></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With