jQuery: post to Twitter with AJAX

jQuery: post to Twitter with AJAX

How to use jQuery, AJAX and OAuth to post tweets to Twitter.

Ricardo Pereira is the author of TwitterOAuth, an efficient PHP wrapper that supports the new Twitter's APIs with OAuth. We can use his excellent work to post tweets to Twitter by using jQuery and AJAX.

Our jQuery code should implement two simple features:

  1. Count the numbers of characters left in a textarea (the Twitter's limit is 140 for each tweet).
  2. Send an AJAX request to a PHP script that makes use of the TwitterOAuth library.

The jQuery code is as follows:


(function( $ ) {
	$.Tweet = function( element ) {
		this.$el = $( element );
		if( this.$el.length ) {
			this.init();
		}	
	}
	
	$.Tweet.prototype = {
		init: function() {
			this.$chars = this.$el.find( "#chars-left" );
			this.$text = this.$el.find( "#tweet" );
			this.$response = this.$el.find( "#response" );
			
			this.count();
			this.send();
		},
		send: function() {
			var self = this;
			self.$el.on( "submit", function( e ) {
				e.preventDefault();
				var tweet = self.$text.val();
				$.post( "lib/ajax.php", { tweet: tweet }, function( data ) {
					if( data.id && /^\d+$/.test( data.id ) ) {
						self.$response.text( "Tweet sent successfully" );	
					}
				});
				
			});
		},
		count: function() {
			var self = this;
			var left = 140;
			self.$text.on( "keydown", function( e ) {
				var code = e.keyCode;
				var remaining = 0;
				if( code !== 8 ) {
					remaining = left--;	
				} else {
					remaining =  left++;
					if( remaining >= left ) {
						remaining = left;
					}	
				}
				
				if( remaining <= 0 ) {
					self.$chars.addClass( "exceed" );
				} else {
					self.$chars.removeClass( "exceed" );	
				}
				
				self.$chars.text( remaining );	
			});
			
			self.$text.on( "paste", function() {
			  setTimeout(function() {
				var value = self.$text.val();
				var rem = left - value.length;
				if( rem <= 0 ) {
					self.$chars.addClass( "exceed" );
				} else {
					self.$chars.removeClass( "exceed" );	
				}
				
				self.$chars.text( rem );
			  }, 300);
			});
			
		}
	};
	
	$(function() {
		var $tweet = new $.Tweet( "#tweet-form" );
	});
	
})( jQuery );

The check performed while we type on the keyboard is rather simple. Instead, the second check bound to the paste event must have a minimum delay in order to get the text inserted in the textarea.

When a POST request is successful, Twitter will return a JSON object that contains the properties of the newly created tweet. We simply test the id property that returns the numeric ID of our tweet.

Our PHP script, ajax.php, requires the TwitterPost class:


require_once( 'TwitterPost.php' );
$tweet = new TwitterPost();
$tweet->send();

TwitterPost is implemented as follows:


require_once( 'Twitter.php' );

class TwitterPost {
	
	private $_connection;
	
	
	
	public function __construct() {
		$settings = array(
			'oauth_token' => 'your token here',
			'oauth_token_secret' => 'your token here',
			'consumer_key' => 'your key here',
			'consumer_secret' => 'your key here',
			'output_format' => 'json'
		);
		$this->_connection = new Twitter( $settings );
        
    }
    
    public function setHeader() {
	    header( 'Content-Type: application/json' );
    }
    
    public function send() {
    	$this->setHeader();
		
		
		
	    $tweet = $_POST['tweet'];
	    $status = '';
	    if( strlen( $tweet ) > 140 ) {
			$status = substr( $status, 0, 140 );    
	    } else {
		    $status = $tweet;
	    }
	    $params = array(
			'status' => $status	
		);
	    $resp = $this->_connection->post( 'statuses/update', $params );
	    echo $resp;
    }
	
		
}

The Twitter class is the original TwitterOAuth class. I've just removed namespaces in order to maximize the compatibility with older PHP versions. You can see the demo and code below.

Complete code

GitHub

Demo