Hi! I’m looking for a solution to track button clicks with addEventListener and display them as a stats counter on the corresponding page in the panel. I’m not sure how to handle the stuff in between, would appreciate any hints, thank you!
What is “the stuff in between”?
Basically, it works like this:
- User clicks button
- JavaScript listens to button click
- Make Ajax call to custom route to update the counter (you can use $page->increment() to update a simple counter field)
- Return updated value to frontend and display in your stats counter.
Thank you so much! The stuff in between was the custom route you mentioned, didn’t know i could is it for that. Got it working!
Here is the simple wip solution i used:
config.php
"routes" => [
[
"pattern" => "tracking/(:any)",
"action" => function ($uid) {
$page = page($uid);
$page->increment("counter");
$page->update(["counterDate" => date("d.m.Y H:i")]);
return [
"status" => "success",
"message" => "Page counter incremented",
];
},
],
],
page.yml:
sections:
stats:
type: stats
size: medium
reports:
- label: Counter
value: "{{ page.counter }}x"
info: "{{ page.counterDate }}"
theme: positive
content:
type: fields
fields:
counter:
type: hidden
default: 0
hide: true
counterDate:
type: hidden
default: 0
hide: true
page.php
<script>
if (document.querySelector('.button')) {
fetch("/tracking/<?= $page->uri() ?>")
.then((response) => response.json())
.then((data) => console.log(data))
.catch(error => {
// something went wrong
});
}
</script>