0

I have a page full of links that go to pdf's I want to track which links are being clicked. I thought I could do something like follows but am having issues:

<?
    function track($link)
    {
    $sql = "UPDATE database WHERE something = 'something';
    $db = new connection();
    $result = $db->query($sql);

    if($result){                 
                  header( 'Location: http://mywebsite/docs/. $link .' ) ;
                }
    }
?>

and my HTML would look like:

<a onClick="track(my_file_.pdf")">File Name</a>

Ok it looks like I am just going to use the link to pass the file name to a php script and once that is done I will redirect the user to the pdf.

0

5 Answers 5

6

you are mixing JavaScript (client-site) with PHP (server-site) - will not work

It look like you want to count how many time pdfs are clicked (delivered) - consider other ways:

  • check access log and count
  • if your PDF is created by script - make update before created
  • execute AJAX request onclick which will update your database
Sign up to request clarification or add additional context in comments.

Comments

3

As mentioned by others you are mixing client side code (the browser code) with the server side code (php). You need to change the html to be

<a href="redirector.php?file=my_file_.pdf">File Name</a>

You then need to create a php script to handle the request. For example redirector.php could look like this:

<?php
function track($link) {
    $sql = "UPDATE database WHERE something = 'something'";
    $db = new connection();
    $result = $db->query($sql);
    if ($result) {
        header('Location: http://mywebsite/docs/' . $link);
        exit;
    }
}

if (isset($_GET['file'])) {
     track($_GET['file']);
}

Comments

2

Try using the href attribute instead of onClick() which is for javascript

Comments

1

you are missing a double quote after 'something' you can't call php function like that after the page is rendered. Go with ajax or a GET/POST to your php script

Comments

1

you should try with jquery ajax

<a onClick="track('my_file_.pdf')">File Name</a>


<script>
function track(link)
{
$.ajax({
  url: "update.php?link="+link,
  success: function(data){
    if(data=="DONE")
    {
        window.location="http://mywebsite/docs/"+link;
    }

  }
});
}
</script>

in update.php

<?php

$link=$_GET['link'];
 $sql = "UPDATE database WHERE something = 'something'";
    $db = new connection();
    $result = $db->query($sql);

    if($result){ 
        echo "DONE";
    }

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.