I’m trying to do AJAX on Twitter REST API (JSON Format). I did the below thing, But, nothing happens.
Not getting any response from server (Twitter). Did I miss something?
function getRecentTweet(){
twitterUsername = document.getElementById("twitterUsername").value;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "http://api.twitter.com/1/statuses/user_timeline/" + twitterUsername + ".json", true);
xhr.send(null);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if(xhr.status == 200) {
var jsonObj = eval(responseJSON);
document.getElementById("twitterStream").innerHTML = jsonObj[0].text;
}
}
}
}
Thanks!
Yes, cross-domain AJAX calls are not allowed. You need to use JSONP.
Make a request to Twitter’s API and append the
callbackparameter. Here’s a sample url:http://api.twitter.com/1/statuses/user_timeline/hulu.json?callback=myFunction
The response from Twitter then will contain executable JavaScript code with the name of the function you specified as the callback parameter. So Twitter’s response looks like:
Since cross-domain is an issue, you need to add a script tag to the page, and set the
srcattribute to the above URL. This can be created and injected into the page dynamically with JavaScript.Then define a global function
myFunctionon the page that always gets called whenever the response from Twitter returns. This too can be predefined or dynamically generated.