Skip to content

Instantly share code, notes, and snippets.

@molovo
Created May 3, 2013 21:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save molovo/5514490 to your computer and use it in GitHub Desktop.
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.
// 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}
@ZoranZilicFTN
Copy link

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment