Tweet to Unlock with jQuery & PHP
Everyone knows how important role Twitter can play to bring new visitors to your site, and Tweet to unlock can only amplify the whole thing by requiring visitors to Tweet about your page in order to unlock the downloadable items or premium content. In this tutorial article, let's create simple "Tweet to Unlock" feature for your web page using jQuery Ajax and PHP.HTML
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
<?php
session_start(); //start PHP session
session_regenerate_id(true); //Generated new session id
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Project</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="tweet_content" class="locked_ct"><h5>Tweet to Unlock this Content</h5>
<a href="https://twitter.com/share" class="twitter-share-button" data-via="saaraan">Tweet</a>
</div>
<script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script>
<script type="text/javascript">
//All event bindings must be wrapped within callback function
twttr.ready(function (twttr) {
//######## trigger when the user publishes his tweet
twttr.events.bind('tweet', function(event) {
/*
To make locked items little more private, let's send our base64 encoded session key
which will work as key in send_resources.php to acquire locked items.
*/
var data = {unlock_key : '<?php echo base64_encode(session_id());?>'};
//Load data from the server using a HTTP POST request.
$.post("send_resources.php", data, function(data)
{
//Append unlocked content into div element
$('#tweet_content').html(data);
}).error(function(xhr, ajaxOptions, thrownError) {
//Output any errors from server.
alert( thrownError);
});
});
});
</script>
</body>
</html>
PHP Ajax Response
When user Tweets the page successfully, an Ajax request is made to PHP file send_resources.php, and the server returns this HTML snippet, which contains unlocked item or anything goes wrong HTTP error is sent to browser.PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
<?php
session_start(); // session start
//retrive base64 encoded post variable and compare it with session id.
if (isset($_POST["unlock_key"]) && base64_decode($_POST["unlock_key"])===session_id())
{
//user unlocked item by tweeting.
echo "Congratulations! You just unlocked this text by Tweeting!";
}else{
//Output HTTP errors
header('HTTP/1.1 500 Oops! something went wrong...');
exit();
}
?>