0

I would like to have a simple system that stores the number of times a link was visited. Basically, on click I would like to call a function that adds 1 to a number of clicks stored in the database (using php).Everything should be happening in the background. Apart from that it should work as a normal link.

<a href="example.com" onclick="CALL PHP FUNCTION;">Link to example.com</a>

How can I call a php function? I think this can be achieved using Jquery. Any advice appreciated.

Vonder
  • 4,033
  • 15
  • 44
  • 61
  • I think you would need to make an ajax call with JS against a php page that had the function for this to work. You can't link directly to the php function. – Gary Storey Apr 14 '15 at 14:23
  • Here you go: http://stackoverflow.com/questions/20738329/how-to-call-a-php-function-on-the-click-of-a-button AND http://stackoverflow.com/questions/19323010/execute-php-function-with-onclick – The Guest Apr 14 '15 at 14:24
  • Also think about what you might need to do to prevent link abuse (if you are in advertising, what you would call click-fraud). – yakatz Apr 14 '15 at 14:24

2 Answers2

6

This would call a specific php page which could then fire your call. In roll-your-own type PHP sites that are very small, I'll build a dispatcher.php that does nothing but call functions. Remember, due to CORS, you wouldn't be able to call a file outside of your site without a more robust solution.

$("a").click(function(){
    $.ajax({
        url: "local-php-link.php", 
        success: function(result){
           alert('it worked')
        }
    });
});
bpeterson76
  • 12,918
  • 5
  • 49
  • 82
0

Doing this with JS seems a bit tricky, you want a PHP code to be executed in the background, so, let's say you want to access example.com through your dns my-website.com. You could just do as following:

<a href="my-website.com/redirect.php?q=example.com"></a>

and then, in your redirect.php page:

<?php
    //my code doing my stuff to increment the thing

    header('Location:' + $_GET['q']);

I will now explain why it would be much better. With JS, the event onclick would be called, but the Ajax is going to block the process, giving the user the feeling that his click didn't worked. As well, in some case, the Ajax call will not work because you clicked on a link, and by default, a link is made to change the page.

Edwin Dayot
  • 248
  • 1
  • 14