skip to Main Content

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


  1. Chosen as BEST ANSWER

    Thanks everyone for your help!

    This is what I've done and works:

    <a class="some-link" id="1" href = "/view-item.php?id=1">View item 1</a><br>
    <a class="some-link" id="2" href = "/view-item.php?id=2">View item 2</a><br>
    <a class="some-link" id="3" href = "/view-item.php?id=3">View item 3</a><br>
    
    <script>
     $('.some-link').on('click',function(){
    
    var id = $(this).attr('id')
    
    
    $.ajax({
        url: "/click-count.php",    
        type: "GET",
        cache: false,
        data:  {
            method: "UpdateClickCount",
            id:id 
         },
        dataType: "json",             
        success: function (data) {
    
        }     
    });
    
    })
    

    The click-count.php is called where the database is updated.


  2. This is how I would have done it

    1. Register a click event.
    2. Prevent its default behavior with event.preventDefault();
    3. Save href attribute’s value
    4. Send an ajax and do the stuff
    5. Now redirect to the url specified in href with location.href = href;
    $(".aLinks").on('click',function(event){
      event.preventDefault();
      var href = $(this).href;
      $.ajax(...).success(function(){
      
       //Do something if you want
       
       location.href = href;
      })
     
    });
    <a href = "/view-item.php?id=1" class="aLinks">View item 1</a>
    Login or Signup to reply.
  3. I think the most straightforward approach is:

    1. register a click event handler on the a elements
    2. prevent the default behavior for the click event.
    3. store the destination page in a new variable
    4. and then do you stuff in your event handler, like XHR
    5. after finishing you stuff, set the window.location.href property to the destination you saved in step 3.

    Here’s some code without using jQuery:

    const manyA = [...document.querySelectorAll("a")];
    manyA.forEach(a => {
      // register the click event
      a.addEventListener("click", event => {
        // prevent the default behaviour
        event.preventDefault();
        // get destination for link
        const destination = event.target.getAttribute("href");
        // do the XHR stuff
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'myservice/username?id=some-unique-id');
        xhr.onload = () => {
          if (xhr.status === 200) {
            alert('User's name is ' + xhr.responseText);
            /// redirect your user to the destination page
            window.location.href = destination;
          }
          else {
            alert('Request failed.  Returned status of ' + xhr.status);
          }
        };
        xhr.send();
        });
    });
    <a href="some.html">Some Link</a>
    <a href="other.html">Some Other Link</a>
    Login or Signup to reply.
  4. 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 db

    function test(e) {
      event.preventDefault();
      console.log(e.target.href);
      return true;
    }
    <a href="/view-item.php?id=1" onclick="test(event)">View item 1</a>
    <a href="/view-item.php?id=2" onclick="test(event)">View item 2</a>
    <a href="/view-item.php?id=3" onclick="test(event)">View item 3</a>
    Login or Signup to reply.
  5. you can set id to a tag and add a event listener to that then call service on back-end to insert to db

    <a class="some-btn" id="btn-1" href = "/view-item.php">View item 1</a>
    <a class="some-btn" id="btn-2" href = "/view-item.php">View item 2</a>
    <a class="some-btn" id="btn-3" href = "/view-item.php">View item 3</a>
    
    <script>
     $('.some-btn').on('click',function(){
    var id = $(this).attr('id')
    //... then send id to your service with ajax or axios
    
    })
    </script>
    
    Login or Signup to reply.
  6. <a> tags can be given an href attribute or an onclick attribute, or both. The onclick attribute can point to a JavaScript function defined elsewhere:

    <body>
      <script type="text/javascript">
      function logClick() {
        console.log("Clicked!");
      }
      </script>
      <a onclick="logClick()">Click Here!</a>
    </body>
    

    This attribute can be assigned in JavaScript with the Element.addEventListener function:

    HTML:

    <a id="link">Click Here!</a>
    

    JavaScript:

    function logClick() {
      console.log("Clicked!");
    }
    
    const aTag = document.getElementById("link");
    aTag.addEventListener("click", logClick);
    

    So create your POST request in a JavaScript function, and pass the function somehow to the HTML <a> element’s click event.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search