Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a tweet from URL using jQuery/JSON/oembed

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?

like image 564
Adamjstevenson Avatar asked May 01 '13 21:05

Adamjstevenson


1 Answers

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>
like image 181
Paul Roub Avatar answered Nov 19 '22 12:11

Paul Roub