0

Trying to make a very simple counter which updates the value in a mysql database table by 1 each time a user clicks on a link.

<a href='http://somesupersite.com' id='246' class='track'>My Link</a>

The javascript that should get the id and pass it to the php script:

$(document).ready(function(){
$('a.track').click(function() {
$.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
});
});

The php script tracker.php should get the post variable and update the mysql database table column:

$id = $_POST['id'];
$con = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPassword, $mysqlDatabase);
mysqli_query($con, "UPDATE table SET clicks = clicks + 1 WHERE id = $id");

I don't get any errors but the database does not update either.

3
  • Var_dump your query and run it into Phpmyadmin Commented Jul 22, 2014 at 11:24
  • Can you echo UPDATE table SET clicks = clicks + 1 WHERE id = $id what it print? Commented Jul 22, 2014 at 11:24
  • Replace Query Line to mysqli_query($con, "UPDATE table SET clicks = clicks + 1 WHERE id = ".$id); Commented Jul 22, 2014 at 11:27

3 Answers 3

1

I suggest you this:

$(document).ready(function(){
    $('a.track').click(function(e) {
       e.preventDefault();
       $.post('http://mysupersite.com/sys/tracker.php', {id:this.id}, function(){
            window.location.href = e.target.getAttribute('href');
       });
    });
});

Make your link navigate from the success callback of your $.post().


The issue seems to me that when you click on the anchor then it just navigates to the href provided page, so this might be possible that the ajax is not getting called.

Sign up to request clarification or add additional context in comments.

Comments

0

Use event.preventDefault() in the context

$(document).ready(function(){
   $('a.track').click(function(event) {
   event.preventDefault();
   $.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
   });
});

Comments

0

Try this:

$(document).ready(function(){
    $('a.track').click(function() {
        console.log("here");
        $.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
    });
});

When you click the a tag, it jumps to the other page. So this function can't work.

If you get the log 'here', it works.

Comments

Your Answer

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