Adding Twitter button to AJAX page

Monday, April 18th, 2011|Beginner tips, Version 4|by Romans

Twitter button is simple to add if you follow official guide. The code produced by the guide would contain a regular link and a JavaScript include. Executing the code would make the button look cool. Here is a sample code:

<a href="http://twitter.com/share" data-count="vertical" data-via="atk4">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Unfortunately this code wouldn’t work if you will try to put it on the AJAX page. AJAX will not allow you to include script from a different domain name for security reasons.

A common way to get around this restriction is to place file locally. However, twitter may decide to change the file, and we will end up with outdated copy. We need to build a proxy instead.

In terms of Agile Toolkit, the proxy would be implemented as a class, which you add to the page. The syntax of such a class would be as straightforward as this:

[php]

$this->add(‘Controller_JSProxy’)
->proxy(‘http://platform.twitter.com/widgets.js’);

[/php]

This adds include to the current page from the specified URL. Below is the implementation of the proxy controller.

[php]

class Controller_JSProxy extends AbstractController {
function proxy($url){
$this->owner->js(true,’$.atk4.includeJS("’.
$this->api->getDestinationURL(
null,array($this->name=>1)).’");’);
if(isset($_GET[$this->name])){
readfile($url);
exit;
}
}
}
[/php]

1 Comment

Romans
Posted April 18, 20119:40 am