I’m building a website where you see a list of external links (like hackernews). There are no single-link pages (like an article page) just a homepage with all the links.
Besides a featured image, title, subtitle, date, I also want to show that how many clicks received each link.
I thought I should use the increment function. Since I’m not really familiar with Ajax call, can you please help me, how can I trigger the increment function with Ajax clicking a link?
As you already experienced, without any condition, the increment function is triggered every time you reload the page, which is not what you want, since you only want to increment the counter if a link is clicked. I’ll get back to you regarding the Ajax call later today.
You’re awesome! It works! But I have a small problem…
When a user clicks on my link, that doesn’t link to a page on my site, but it leads to an external page, like a Facebook post.
So, I tried your version, and if I set it to link to one of my page, your solution works, but my goal is to immediately direct the user to an external page.
So in my code block, the box_link() leads to an external (mostly Facebook post URL) set by the editor in the Kirby Panel, so I cannot put anything into the article.php because that doesn’t get loaded along the way. Do you have an idea how we can get around that?
They have a text file, that’s not a problem. The problem is that the user will never land on the article.php subpage.
Imagine like this:
I have a page with full of boxes (let’s call this page a blog page for convenience). The editor can add a new box to this blog page by creating a new subpage in the Kirby admin panel. So each of these boxes have their own folder with own .txt file in it.
Each box has a featured image, a title, a short description, a date and most importantly a custom URL. So when the user clicks on one of these boxes on the blog page, it will link to this custom url, which is outside of my webpage (it will be URLs of various Facebook posts) instead of loading in the article template. Next to the date I also want to add this click view number that we’re focusing on now.
So each box acts like a small article (have separate txt files) and looks like blog posts on a blog page, but when the user clicks on them, the user will end up on a Facebook page, rather than an article page on my website.
So this is why it won’t work putting code in the article.php file, because that won’t be loaded along the way. But I still have separate txt files available for storing specific click numbers for each and every box.
Then you probably have to prevent the default link action in your Javascript, call a route that does the incrementing and on success redirect to the Facebook post.
The only difference is that there is no increment method anymore, so you would have to use $page->update()(which requires an authenticated user or the Almighty, i.e. $kirby->impersonate('kirby')).