In a WordPress projet, let say I want my users to click on a button when they aggree with a sentence such as :
If you like pancakes click here <button> YES I DO </button>
Let say I want to display the number of clicks such as :
<nb_click> have allready say yes
Question 1 :
Is there a plugin that does this ?
Question 2 :
I tried to do it with a code snippet (php/javascript ; Elementor short code widget): But I am facing a probleme with the execution evironnement.
PROBLEM : The php code is executed as soon as the web page loads. It looks like the execution environnement had removed the javascript code to execute only php tags. And when the user click on the button, the javascript code is executed (as if it had reappeared). The function counter_increment_and_update_db()
is well triggered, but the php code is not executed.
at the end, the incremented value of the counter is always inserted into the database, no matter the button was clicked or not
<?php
$current_counter_value = get_counter_value_from_db();
?>
<button onclick="counter_increment_and_update_db()"> OUI </button>
<span id="counting"></span>
<script>
html_display_curent_counter_value(<?php echo $current_counter_value; ?>)
function counter_increment_and_update_db() {
<?php
$incremented_value = increment_by_one($current_counter_value);
?>
html_display_curent_counter_value(<?php echo $incremented_value; ?>)
<?php
update_db_counter_value($incremented_value);
?>
}
// ----------------- javascript UTIL FUNCTIONS ----------------
function html_display_curent_counter_value(text_to_be_displayed){
document.getElementById("counting").innerText = text_to_be_displayed;
}
</script>
<?php
// --------------------------------------------------------------------
// ----------------- php UTIL FUNCTIONS ----------------
// --------------------------------------------------------------------
function increment_by_one($value){
$out=$value+1;
return $out;
}
function get_counter_value_from_db(){
global $wpdb;
$wpdb->show_errors();
$query = "SELECT * FROM click_counter WHERE counter_name = 'sondage1'";
$resultArray = $wpdb->get_results($query);
$current_counter_value = get_last_value($resultArray);
return $current_counter_value;
}
function get_last_value($array_of_values){
$out=0;
foreach ($array_of_values as $page) {
$out = $page->counter_value;
}
return $out;
}
function update_db_counter_value($new_value) {
global $wpdb;
$wpdb->show_errors();
$wpdb->update(
'click_counter',
array(
'counter_value' => $new_value
),
array(
'counter_name' => 'sondage1'
),
array(
'%d'
)
);
}
?>