Made ajax call as a function to avoid the Console Error 400 Post. It opens the channel and I was able to get the parameters passed.
counter.js
jQuery(document).on('click','.counter',function(e){
testAjax(the_ajax_script.ajaxurl);
});
function testAjax(link) {
$.ajax({
url: link,
type: 'post',
data: {
'action': 'set_button_count',
'increase' : '1'
},
success: function(data) {
jQuery('.count').html(data);
}
});
}
In functions.php I changed the $counterFile variable value to the link of a text file, which I uploaded via the WordPress admin panel.
I specified the link as the server directory path, to avoid the error[“failed to open stream: HTTP wrapper does not support writeable connections”].
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="/home/example/public_html/wp-content/uploads/2019/06/counter.txt";
if ( isset($_POST['increase']) )
{
if ( ( $counter = @file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter);
echo file_get_contents($counterFile);
wp_die();
}
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) ;
}
wp_die();
}
add_action('wp_ajax_nopriv_set_button_count', 'set_button_count');
add_action('wp_ajax_set_button_count', 'set_button_count');
Hope it helps someone.