Daniel
Daniel

Reputation: 1

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.

Different ways to do, but that's the way I finally did it:


MAIN HTML FILE:

<title>Twitter API  JSON</title>

<script type="text/javascript">

    //function that created the AJAX object
function newAjax(){
      var xmlhttp=false;
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (E) {
            xmlhttp = false;
         }
      }
      if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
         xmlhttp = new XMLHttpRequest();
      }
   return xmlhttp;
}  

//function that search the tweets containing an specific word/sentence
function gettweets(){

      ajax = newAjax();

     //ajax call to a php file that will search  the tweets
      ajax.open( 'GET', 'getsearch.php', true);

      // Process the data when the ajax object changes its state
      ajax.onreadystatechange = function() {
         if( ajax.readyState == 4 ) {
            if ( ajax.status ==200 ) {  //no problem has been detected

        res = ajax.responseText;
        //use eval to format the data
        searchres = eval("(" + res + ")");

        resdiv = document.getElementById("result");
                    //insert the first 10 items(user and tweet text) in the div
        for(i=0;i<10;i++){
            resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
        }


            }
         }
      }

    ajax.send(null);
}  //end gettweets function

</script>




#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>


</html>

PHP WHERE WE GET THE JSON DATA:

$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";

$json = file_get_contents($jsonurl,0,null,null);

echo $json;

And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:

MAIN HTML FILE:

//same code above

//ajax call to a php file that will search  the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);

//same code above

I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?

Upvotes: 0

Views: 4035

Answers (2)

Ryan McGrath
Ryan McGrath

Reputation: 2042

XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.

That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100312

You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Upvotes: 0

Related Questions