Created
May 3, 2013 21:51
-
-
Save molovo/5514490 to your computer and use it in GitHub Desktop.
A simple AJAX download counter. Count is stored in a json file, and updated via PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jQuery to update counter when button is clicked | |
$('#download').click(function(event) { | |
event.preventDefault(); | |
var redirectUrl = $(this).attr('href'); | |
$.ajax({ | |
url: "downloads.php", | |
success: function(response) { | |
if (response = 'success') { | |
// The counter file has been updated in the background, but we should update the results on screen to tell the user | |
var count = $('#count').html(); | |
$('#count').html(parseFloat(count) + 1); | |
// Then redirect so that file can download | |
window.location.href = redirectUrl; | |
} | |
} | |
}); | |
return true; | |
}); | |
// jQuery to get the current count on page load | |
$.ajax({ | |
url: "get-downloads.php", | |
success: function(data) { | |
var data = JSON.stringify(data, null, 4); | |
var data = $.parseJSON(data); | |
$('#count').html(data.count); | |
} | |
}); | |
// contents of downloads.php | |
<?php | |
$file = "downloads.json"; | |
$json = json_decode(file_get_contents($file), true); | |
$json['count'] = $json['count'] + 1; | |
file_put_contents($file, json_encode($json)); | |
echo 'success'; | |
?> | |
// contents of get-downloads.php | |
<?php | |
$file = "downloads.json"; | |
$json = json_decode(file_get_contents($file), true); | |
header('Content-Type: application/json'); | |
echo json_encode($json); | |
?> | |
// contents of downloads.json as a starting point | |
{"count":1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice