I'm trying to create a button click counter that on every download it increases. I want to use it without a database, this is the code:
<?php
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_GET['increase']) )
{
if ( ( $counter = @file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if ( ! $counter = @file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
<script type="text/javascript">
jQuery(document).on('click','a#download',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
</script>
<div id="counter"><?php echo $counter ; ?></div>
<a href="<?php echo get_field("pdf"); ?>" id="download" onclick="window.open(this.href);return false;">Download btn</a>
The problem is that when I click on Download btn
the pdf opens but the number dissapear, and if I reload the page it always stays at 0
. Any idea where or what is the problem?
The reload is down to the link being clicked (it is still a link after all, which will reload the page).
Either return false:
jQuery(document).on('click','a#download',function(){
...
return false;
});
Or prevent the default action with preventDefault()
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
...
});
You are currently using both an onclick=
attribute and a jQuery event handler on the same button. That is not a good situation.
Best to use only jQuery for the handlers. e.g.
jQuery(document).on('click','a#download',function(e){
e.preventDefault()
window.open(this.href);
... The other code ...
});
and remove the onclick="window.open(this.href);return false;"
from the button.