On a webpage I have several links to items, for example:
<a href = "/view-item.php?id=1">View item 1</a>
<a href = "/view-item.php?id=2">View item 2</a>
<a href = "/view-item.php?id=3">View item 3</a>
For SEO reasons I want to have a normal ahref, but when someone clicks on the link, I want to register the click in a database so I can see how many times an item has been clicked on.
I think somehow with an Ajax call that will register the click in the database, but not sure.
6
Answers
Thanks everyone for your help!
This is what I've done and works:
The click-count.php is called where the database is updated.
This is how I would have done it
event.preventDefault();
location.href = href;
I think the most straightforward approach is:
click
event handler on thea
elementsclick
event.window.location.href
property to the destination you saved in step 3.Here’s some code without using jQuery:
You can add an
onclick
handler and prevent the default behavior using the event.preventDefault.Inside this function make the request to save the data to dbyou can set id to
a
tag and add a event listener to that then call service on back-end to insert to db<a>
tags can be given anhref
attribute or anonclick
attribute, or both. Theonclick
attribute can point to a JavaScript function defined elsewhere:This attribute can be assigned in JavaScript with the
Element.addEventListener
function:HTML:
JavaScript:
So create your POST request in a JavaScript function, and pass the function somehow to the HTML
<a>
element’sclick
event.