When the user clicks class count the counter should work:
<div class="pop-btn" class="counter"><a href="https://www.example.com">Know More</a></div>
<div class="count"></div>
The problem is that I want the number to be saved, so for example:
user #1 clicks on the div with class "counter" 10 times
user #2 opens the site and the count is at 10, he clicks and now the counter starts 11 and so on with new users.
I'm trying to do this to keep track of how many times a file has been downloaded.
Any idea how can I do that?
Here is the code I have:
functions.php
function js_enqueue_scripts() {
wp_enqueue_script ("my-ajax-handle", get_stylesheet_directory_uri() . "/js/counter.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");
function set_button_count(){
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_POST['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) ;
}
}
add_action('wp_ajax_nopriv_set_button_count', 'set_button_count');
add_action('wp_ajax_set_button_count', 'set_button_count');
Counter.js
jQuery(document).on('click','.counter',function(){
jQuery('.count').html('Loading...');
var ajax = jQuery.ajax({
method : 'post',
url : the_ajax_script.ajaxurl, // Link to this page
data : { 'action':'set_button_count','increase' : '1' }
});
ajax.done(function(data){
jQuery('.count').html(data) ;
});
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable');
});
});
Console Error: Error 400 Post /wp-admin/admin-ajax.php
data : { 'increase' : '1' }
should include the AJAX action -data : { 'increase' : '1', action: 'more_post_ajax' }
.