jQuery: postare tweet su Twitter con PHP e AJAX

jQuery: postare tweet su Twitter con PHP e AJAX

Ricardo Pereira è l'autore di TwitterOAuth , un efficiente wrapper PHP che supporta le nuove API di Twitter con OAuth. Possiamo usare il suo eccellente lavoro per pubblicare tweet su Twitter usando jQuery e AJAX.

Il nostro codice jQuery dovrebbe implementare due semplici funzionalità:

  1. Contare il numero di caratteri rimasti in una textarea.
  2. Invia una richiesta AJAX a uno script PHP che faccia uso della 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 );

Il controllo eseguito mentre scriviamo sulla tastiera è piuttosto semplice. Invece, il secondo controllo associato all'evento paste deve avere un ritardo minimo per ottenere il testo inserito nella textarea.

Quando una richiesta POST ha esito positivo, Twitter restituirà un oggetto JSON che contiene le proprietà del tweet appena creato. Testiamo semplicemente la proprietà id che restituisce l'ID numerico del nostro tweet.

Il nostro script PHP, ajax.php , richiede 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 è la classe originale di TwitterOAuth. Ho solo rimosso i namespace per massimizzare la compatibilità con le versioni precedenti di PHP. Puoi vedere la demo e il codice qui sotto.

Codice completo

GitHub

Demo

Torna su