Latox
Latox

Reputation: 4695

Firing a script on click?

Say I have a URL:

<a href="hello.html" id="4298">hello</a>

When someone clicks this link, I want it to fire a script off using ajax so we can track how many times this link has been clicked behind the scene.

My page is called track.php which will pull the ID 4298 via GET, track.php?id=4298 and then it updates the database respectively.

How would I go about coding this in javascript/ajax so upon this link being clicked, in form of an "onclick event", this track.php will be ran behind the scene?

Upvotes: 1

Views: 218

Answers (3)

tjdett
tjdett

Reputation: 1723

Keep in mind that to do a request in the background, you will need to wait for the AJAX response to follow the click. If that's what you want, then using jQuery:

<script type="text/javascript">
var track = function(obj) {
  $.ajax({
    url: "track.php?id="+obj.id,
    success: function(){
      window.location.href = obj.href;
    }
  });
  return false;
};
$('a').click(track);
</script>

Upvotes: 1

alex
alex

Reputation: 490143

var anchors = document.body.getElementsByTagName('a');

for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {

   a.onclick = function(event) {

       event.preventDefault();
       var id = this.id,
           xhr = new XMLHttpRequest();

       xhr.open('track.php?id=' + id);

       xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
             if(xhr.status == 200) {
                 window.location = this.href;
             }
          }
       }  
       xhr.send();  
   }
}

Keep in mind that XMLHttpRequest() doesn't support older versions of IE.

If you are using jQuery, use the library's AJAX functions.

Upvotes: 0

aroth
aroth

Reputation: 54796

<script>
    window.doTheThing = function() {
        //send a request to your 'track.php' URL here 
    };
</script>

<a href="hello.html" id="4298" onclick="doTheThing(); return false;">hello</a>

Upvotes: 0

Related Questions