4

I'm relatively new to JavaScript and decided to try and access Twitter through the API to get my 5 latest tweets however I'm running into difficulty and I would be grateful for some help.

This is the tweets.js code. I've looked carefully at the API to form this but not sure if it is right.

tweets = {
    loaddata: function() {
        $.ajax({
            url: 'https://api.twitter.com/1.1/statuses/user_timeline.json',
            type: 'GET',
            dataType: 'json',
            data: {
                screen_name: 'techybox',
                include_rts: false,
                count: 5,
                include_entities: true
            },
            success: function(data, text) {
                var html = '<li class="tweet">TWEET</li>';
                $('#timeline').append(html.replace('TWEET', tweets(data.text)));
            }
        });
    };
}

$(document).ready(function() {
    tweets.loaddata();

});

In theory that should load the 5 latest tweets and append them to the UL with the id timeline. I've seen that you may need OAuth to do this but I was unsure how i would implement this? Am I correct? Twitter's old API seemed to work without this but 1.1. may have changed with this?

Finally here is my html page that just contains the UL:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tweets</title>
</head>
<body>
    <h1>Tweets</h1>
    <ul id='timeline'></ul>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="tweets.js"></script>
</body>
</html>
5
  • are you seeing any error in the console? Commented Apr 7, 2016 at 18:55
  • you had an extra bracket, here is the correct code, can you try it with your api info? jsfiddle.net/pjz1fzzg Commented Apr 7, 2016 at 19:00
  • Thanks for spotting that, it still doesn't seem to work. Should I looked at OAuth? Commented Apr 7, 2016 at 19:08
  • I am almost positive you need to use OAuth with the twitter API... Commented Apr 7, 2016 at 19:13
  • You might like to check out the Twit library which makes the OAuth part a breeze github.com/ttezel/twit Commented Feb 21, 2022 at 11:07

2 Answers 2

7

Twitter's updated API requires oAuth, which would require you to write a server-side component that gets used by your javascript.

So it's not that your methodology is wrong. Twitter just doesn't want you to get the information that way anymore.

Notice if you go to the API in a browser, you'll just get an error. https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=techybox&count=3

There's a really good post here about the subject: Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot :) From a bit of reading on OAuth, I need a server-side component rather than just implementing it into Javascript as recommended by twitter
2

Use oauth from here

var oauth = require('oauth.js');

var urlLink = 'https://api.twitter.com/1.1/statuses/update.json';

var twitterStatus = "Sample tweet";

var oauth_consumer_key = "d6T0PcnqxxxxxxxxxxUB7Jok2f";
var consumerSecret = "NFbG1H7CGRxukJTPxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxze02qH8";

var oauth_token = "306673734-RQanTkxxxxxxxxxxxxxxxxxxeH4NuqQ8Z";
var tokenSecret = "YnF5vpjclMMVWhuxxxxxxxxxxxxxxxl3xejqAu";

var nonce = oauth.nonce(32);
var ts = Math.floor(new Date().getTime() / 1000);
var timestamp = ts.toString();

var accessor = {
    "consumerSecret": consumerSecret,
    "tokenSecret": tokenSecret
};

var params = {
    "status": twitterStatus,
    "oauth_consumer_key": oauth_consumer_key,
    "oauth_nonce": nonce,
    "oauth_signature_method": "HMAC-SHA1",
    "oauth_timestamp": timestamp,
    "oauth_token": oauth_token,
    "oauth_version": "1.0"
};
var message = {
    "method": "POST",
    "action": urlLink,
    "parameters": params
};

//lets create signature
oauth.SignatureMethod.sign(message, accessor);
var normPar = oauth.SignatureMethod.normalizeParameters(message.parameters);
var baseString = oauth.SignatureMethod.getBaseString(message);
var sig = oauth.getParameter(message.parameters, "oauth_signature") + "=";
var encodedSig = oauth.percentEncode(sig); //finally you got oauth signature

$.ajax({
    url: urlLink,
    type: 'POST',
    data: {
        "status": twitterStatus
    },
    beforeSend: function(xhr){
        xhr.setRequestHeader("Authorization",'OAuth oauth_consumer_key="'+oauth_consumer_key+'",oauth_signature_method="HMAC-SHA1",oauth_timestamp="' + timestamp + '",oauth_nonce="' + nonce + '",oauth_version="1.0",oauth_token="'+oauth_token+'",oauth_signature="' + encodedSig + '"');  
   },
   success: function(data) { 
        alert("Tweeted!"); 
   },
   error:function(exception){
       alert("Exeption:"+exception);
    }
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.