Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Twitter v1.1 API in javascript using AJAX

Aim - to get the twitter followers of a particular user using javascript

I have tried the below code as a POC-

$(document).ready(function() {
    // Handler for .ready() called.

    $.ajax({
        url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
        type: "GET",
        data: { cursor: "-1", 
                screen_name: "twitterapi" },
        cache: false,
        dataType: 'json',

        success: function(data) { alert('hello!'); console.log(data);},
        error: function(html) { alert(html); },
        beforeSend: setHeader
    });


    function setHeader(xhr) {
        if(xhr && xhr.overrideMimeType) {
            xhr.overrideMimeType("application/j-son;charset=UTF-8");
        }

        //var nonce = freshNonce();
        //var timestamp = freshTimestamp();
        //var signature = sign(nonce,timestamp);

        //alert(signature);
        //alert(accessToken+"-"+consumerKey);
        //alert(oauth_version+"-"+oauth_signature_method);
        xhr.setRequestHeader('Authorization','OAuth');
        xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
        xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
        xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
        xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
        xhr.setRequestHeader('oauth_timestamp', '1359955650');
        xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
        xhr.setRequestHeader('oauth_version', '1.0');
    }

});

I calculated the signature values from the Twitter OAuth tool .. This gives me 400 Bad Request error ....

Please let me know what the problem is...

like image 687
user2015233 Avatar asked Feb 04 '13 06:02

user2015233


People also ask

Can we call API from Ajax?

AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here.


1 Answers

The problem is your request's header, it should be like this:

xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');

Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a

It support both client side and node.js

Cheers

like image 82
Ddo Avatar answered Sep 28 '22 01:09

Ddo