Pubblicare un tweet su Twitter con jQuery ed AJAX

Pubblicare un tweet su Twitter con jQuery ed AJAX

Ricardo Pereira è l'autore di TwitterOAuth, un'ottima libreria PHP che supporta le API di Twitter con OAuth. Possiamo usare questa libreria per pubblicare i nostri tweet su Twitter usando jQuery ed AJAX.

Il nostro codice jQuery deve:

  1. contare il numero di caratteri rimasti per ogni tweet (il limite è 140)
  2. inviare una richiesta AJAX ad uno script PHP che implementa la libreria TwitterOAuth.

Il codice jQuery è il seguente:


(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 );

La verifica effettuata mentre si digita sulla tastiera è semplice. Effettuiamo anche una seconda verifica con l'evento paste ma in questo caso abbiamo bisogno di impostare un ritardo minimo nell'esecuzione del codice per selezionare il testo inserito.

Quando una richiesta POST ha successo, Twitter restituisce un oggetto JSON con le proprietà del tweet appena creato. Possiamo usare questo oggetto per stabilire se la richiesta AJAX ha avuto successo.

Il nostro script PHP, ajax.php, usa la classe TwitterPost:


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

TwitterPost è implementata come segue:


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;
    }
	
		
}

La classe Twitter è l'originale TwitterOAuth da cui sono stati rimossi i namespace per renderla compatibile con le versioni meno recenti di PHP.

Codice completo

GitHub

Demo

Torna su