jQuery – PHP & Ajax with the Twitter API

Just Posted: Apple Likely to Give Education Rather than Resolution for iPhone 4 Antenna Issues

So for today’s blog post I am going to show you how you can use jQuery, PHP and a little ajax to connect up to the Twitter API and return results. I’ll cover off unauthenticated calls today to the search API, and follow up with the authenticated piece a little later, so watch out for that!

PHP using cURL

So, in order for us to talk to the Twitter API, we need to use cURL. This isn’t a hard and fast rule, but it sure does make our lives easier. The cURL library should be installed as part of your PHP installation, but do check.

cURL allows us to make a simple call to the Twitter API, and grab some results back if necessary. I’ll be using XML to return results for this demo, but you can use JSON if you want. Anyway, without further ado, here is a nice piece of PHP code to talk to the Twitter Search API – so create a file called getSearch.php :

<?php

$query = $_POST['query'];

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://search.twitter.com/search.atom?q=" . urlencode($query) . "&amp;amp;amp;rpp=10");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);

header('Content-Type: application/xml; charset=ISO-8859-1');

print $result;
?>

So, lets quickly explain this. The PHP script will take POST data, in this case a query, and send the query to the Twitter Search API. The Twitter API is also taking an rpp parameter, which is the number of results to be returned. It will then return XML, and also print it out as a valid XML document. Job done. Obviously there is no error handling, this is the bare bones – I will let you deal with all of that!

The jQuery

The jQuery side is also pretty straight forward… It’ll do an ajax post call to our PHP script, and go through the XML returned and paste it into a location in your DOM HTML. So, create a controller.js file and put this code into it:

var timer;

$(document).ready(function() {

getSearch();

});

function getSearch()
{
clearTimeout(timer);
var results;
var theQuery = "stevereynolds";

$.post("/getSearch.php", {query: theQuery},  function(xml){
$('entry',xml).each(function(i){
var title = $(this).find("title").text();
results = title + "<BR>";
});
$("#container").html(results);
});

timer = setTimeout('getSearch()', 30000);
}

So this code sets the query parameter to “stevereynolds”, makes an ajax post to our getSearch.php file, and then runs through the returned XML. It firstly searches for the “entry” node, and then the “title” parameter as part of each “entry” node in the XML. Lastly, it applies the results to a container in your DOM called “container”. This function also runs every 30 seconds, see the setTimeout for that part.

Putting it all together

So, putting it together is pretty darn easy. Create an HTML page in the same directory as all of the above, with the following:

<HTML>
<HEAD>
<script src="jquery-1.3.1.js"></script>
<script src="controller.js"></script>
</HEAD>
<BODY>

<DIV id="container"></DIV>

</BODY>
</HTML>

Thats it! When you load your HTML it will call the controller.js -> which in turn will call the javascript function getSearch() to return Twitter Search API results every 30 seconds.

Download IconFeel free to download this code and reuse as you want. As I said, it’s very simplistic – so go ahead and adapt this with lots more jQuery lovelyness! Feel free to share back your fine work! Also see my new article discussing making authenticated calls to the Twitter API.

Further Reading:

Learning jQuery

Learning jQuery

Amazon Kindle 2

Amazon Kindle 2

jQuery Reference Guide

jQuery Reference Guide

80 Responses to “jQuery – PHP & Ajax with the Twitter API”

  1. Hi, nice tutorial, but I’m curious. Why not use $.getJSON with a callback function (you can use it cross domain), and remove the PHP entirely? As an added bonus, you won’t have to deal with XML, and it will work without cURL too.

  2. Steve Reynolds says:

    Hey – thanks for the great feedback – I haven’t played with JSON but this will be even easier it sounds… thanks!

  3. Hi Steve, hope you don’t mind, but I wrote up a quick post on $.getJSON! Looking forward to your post on authenticated use of the API!

  4. Steve Reynolds says:

    All good my friend! I’ll post an authenticated article over the weekend/Monday

  5. Patternhead says:

    Great article Steve. Thanks for sharing.

    Look forward to reading the post on authenicated access.

  6. Steve Reynolds says:

    Thank you :-) API calls using authentication will be tomorrow hopefully!

  7. Adnan Osmani says:

    I just blogged about this jQuery plugin for displaying Twitter feeds. It’s quite useful and if nothing else provides a great example of how jQuery can be used to parse RSS feeds. Great work!

    http://blarnee.com/wp/a-jquery-and-twitter-plugin/

  8. mcpaige says:

    Steve, in the example given how can you STOP the timer !

  9. Steve Reynolds says:

    The timer is stopped by this piece of code: clearTimeout(timer);

    You can call that at any point and it will cancel the timer.

    HTH. Steve

  10. shep says:

    hey steve-

    how would i query multiple terms in the var theQuery = row?

  11. Nick says:

    Hey,

    I’m going to play around with this, but I would like to know the same thing as shep.

    I’d like it to return results for any of the terms I list. Is that possible?

  12. steve says:

    Hi Steve, thanks for this great little add-on, but I was wondering, I’ve set the code to only pull one result per query, is there a way to clear the past query before writing the new results? I would like to put the results in a small space that would only hold one results at a time. Thanks,
    Steve

  13. Steve Reynolds says:

    Hi steve,

    To clear the container, simply do this: $(“#container”).html(“”);

    This will empty it of any code, ie your previous query result…

  14. Steve Reynolds says:

    Shep / Nick,

    Can you not just set the query to multiple terms? var = “stevereynolds jquery”; ?

  15. steve says:

    Steve,

    Thanks for the help, you’re right it does clear the previous posts, but when it query’s it again, it still returns ALL of my previous posts, I want it to pull ONLY my last post.

    Does that make sense? I hope I’m explaining my wants clearly enough.

    Thanks again,
    Steve

  16. nick says:

    I just tried thing and I get no results when viewing the html page on my web server. I know there are results for my search term. Any ideas?

  17. Yasir says:

    thanks for the tutorial its what i was looking for works perfect can you help me here please how i can get the name (screen name) or other tags using your code ?

    thanks in advance

  18. Steve Reynolds says:

    This part : $(this).find(“title”).text()

    Gets the “title” node from the XML that the Twitter API returns.

    There should be a “name” node in the returned XML, so just update the jQuery code…

  19. Casey says:

    anybody know how to get it to display the username for each tweet result with a linkback to that twitter users profile?

  20. Ian says:

    Thanks for the article, just what I was after by the look of it. Is there a demo of this to see how it works?

  21. fabian says:

    Hi Steve,

    I downloaded you code and started testing it, but it doesn’t do anything! I didn’t alter anything yet. What’s going wrong?

    http://www.fabiandesign.nl/twitter/index.html

  22. rob ganly says:

    good stuff steve.

    quick not for those geting the demo code on this page to run:

    the current code in controller.js will only display one of the results retrieved as-is, so in order display them all simply change the results assignation line to append rather than overwrite.

    results = title + “”;
    to
    results += title + “”;

    best,

    rob ganly

  23. Steve Rifkin says:

    steve this was so helpful. I just wanted to tip my noob hat.

  24. david nahmias says:

    Please help!

    I run this code , when i run getsearch.php i get an error . you must enter a query.

    what i am doing wrong.

    Thank You!

    David

  25. Hello, about php, twitter api and xml, use SimpleXML to read the content in $result.

    $result is an array so treat it like one. Use (string) to show the results

    If you only use
    echo $result->user->id or something, the result won’t show up and the thing missing is (string)

    Lo descubri tratando de usar la api de twitter con php

    Espero les sea util (i hope this can be useful)

    @chepe263

  26. Steve Reynolds says:

    Thanks for the helpful addition :)

  27. James says:

    If you want to grab more information, show the image of the user and have multiple tweets**, put the following in the getSearch() function (**only for multiple tweets do you need the vars as Arrays):

    var title = new Array();
    var name = new Array();
    var uri = new Array();
    var image = new Array();
    var id = new Array();
    

    And then there is the function that grabs the XML data (Once again if you have multiple tweets then you put the [i] after the variable names, otherwise you can drop it):

    $.post("getSearch.php", {query: theQuery},  function(xml){
    $('entry',xml).each(function(i){
    title[i] = $(this).find("title").text();
    name[i] = $(this).find("name").text();
    uri[i] = $(this).find("uri").text();
    image[i] = $(this).find("link[rel='image']").attr("href");
    id[i] = $(this).find("id").text();
    

    Then this code goes where the results are, outside the $(‘entry’,xml).each(function(i)

    results = "<a href='" + uri[0] + "' rel="nofollow">" + name[0] + "</a>" + " " + title[0] + "";
    results2 = "<a href='" + uri[1] + "' rel="nofollow">" + name[1] + "</a>" + " " + title[1] + "";
    results3 = "<a href='" + uri[2] + "' rel="nofollow">" + name[2] + "</a>" + " " + title[2] + "";
    $("#container").html(results);
    $("#container2").html(results2);
    $("#container3").html(results3);
    

    Make sure to add the other container divs to the HTML.

    
    

    Enjoy!

  28. ErrWTF? says:

    Heya… what about error handling? JSONP is a real B when it comes to *real* error handling.

    Ohhh, set a timeout he says. Nope. Kinda shaky.

  29. asq says:

    i like script thank.

  30. vipin sahu says:

    hi
    when i download your script and upload in to my host its not working how can use this script thanks
    http://s-series.co.in/twitter/ this is the url where i uploaded files

  31. Harris Lulas says:

    Hello I am so delighted I found your blog, I really found you by mistake, while I was looking on Yahoo for something else, Anyways I am here now and would just like to say thanks for a tremendous post and a all round entertaining blog (I also love the theme/design), I don

  32. Jake Gomez says:

    i always update my Twitter and i love to twitter my daily activities to my friends and loved ones. i also maintain a personal blog for entries which requires more detail.

  33. Jason says:

    Thanks for the info. I couldn’t locate something like this anywhere.

  34. fridaycheap says:

    when i download your script and upload in to my host

  35. hi
    when i download your script and upload in to my host its not working how can use this script thanks
    http://frontlinedogs.org this is the url where i uploaded files

Trackbacks/Pingbacks

  1. [...] Steve Reynolds recently wrote a blog post showing how to access the twitter search API using PHP, cURL, and JQuery. [...]

  2. [...] jQuery – PHP & Ajax with the Twitter API | Steve Reynolds Blog (tags: webdev php jquery ajax twitter) [...]

  3. [...] jQuery – PHP & Ajax with the Twitter API | Steve Reynolds Blog [...]

  4. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  5. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  6. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  7. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  8. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  9. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  10. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  11. [...] jQuery – PHP & Ajax with the Twitter API | Steve Reynolds Blog Quick and easy look at the Twitter API w/ php and ajax (tags: jquery javascript twitter development php api) [...]

  12. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  13. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  14. [...] jQuery – PHP & Ajax with the Twitter API | Steve Reynolds Blog A jQuery twitter ajax example. (tags: jquery twitter ajax) [...]

  15. [...] jQuery – PHP & Ajax with the Twitter API | Steve Reynolds Blog. [...]

  16. [...] 2-) jQuery,PHP,Ajax ve Twitter API ile Çalışan Twitter Okuyucusu [...]

  17. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  18. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  19. [...] PHP and jQuery for Twitter API Tutorial shows how you can use jQuery, PHP and a little Ajax to connect up to the Twitter API and [...]

  20. [...] Authenticating Twitter API calls with PHP & jQuery [...]

  21. [...] 5. jQuery – PHP & Ajax with the Twitter API [...]

  22. [...] jQuery – PHP & Ajax with the Twitter API [...]

  23. [...] jQuery – PHP & Ajax with the Twitter API [...]

  24. [...] jQuery – PHP & Ajax with the Twitter API [...]

  25. [...] jQuery – PHP & Ajax with the Twitter API So for today’s blog post I am going to show you how you can use jQuery, PHP and a little ajax to connect up to the Twitter API and return results. I’ll cover off unauthenticated calls today to the search API, and follow up with the authenticated piece a little later, so watch out for that! [...]

  26. [...] 11. jQuery – PHP & Ajax with the Twitter API [...]

  27. [...] – put twitter on your website with tweet!, an unobtrusive javascript plugin for jquery.PHP and Ajax with the Twitter API – a tutorial that’ll show you how to use jQuery, PHP and a little AJAX to connect to [...]

  28. [...] التعامل مع الواجهة البرمجية لتويتر (API) بإستخدام الأجاك… [...]

  29. [...] jQuery – PHP & Ajax with the Twitter API [...]

  30. [...] Query – PHP & Ajax with the Twitter API [...]

  31. [...] PHP and Ajax with the Twitter API This tutorial shows you how to use jQuery, PHP and a little AJAX to connect to the Twitter API and return results. [...]

  32. [...] jQuery – PHP & Ajax with the Twitter API [...]

Leave a Reply