Need help with simple Jquery Ajax script to track links

Hi all,

Our goal is to track (by name) who clicked on specific links on our website.

We have a PHP login system to identify users. I have a simple list of links:

<ul id="linkList">
  <li><a href="#">Link One</a></li>
  <li><a href="#">Link Two</a></li>
  <li><a href="#">Link Three</a></li>
</ul>

My Jquery script passes the name of the link via an AJAX GET request to the server:

$('#linkList a').click(function() {
	$.get('links.php', {'link': $(this).text()});
});

“links.php” simply inserts the link name and $_SESSION[‘username’] into a table in our database.

This works fine, until I edit one of the links to include an actual link (instead of just “#”).

In other words, if I edit the first link to include a link to cnn.com like this:

<li><a href="http://www.cnn.com">Link One</a></li>

…clicking the link takes me to cnn.com, but the AJAX stuff is ignored. How can I do both, i.e., keep the link active AND do the AJAX call to the server?

Thanks, your method works, although it means hard-coding the URL’s and link names as queries. The Jquery method conveniently writes the query for me.

I am still hoping for an answer to the original question just for the sake of it. I’d like to know if it’s possible to perform an AJAX request AND have a link behave normally. Not sure if it can be done or not.

Why wouldn’t you do this server side on page loads?

Some of the links are to external sites. Others are links to downloadable PDF’s.

Route those through your server which will do the redirects using header('location: ’ . OUTSIDE_SITE);

Yup - just put onclick=“return false” in your <a> tag (you may or may not be able to move that into your external javascript code somewhere - it’s been a while since I’ve done it so can’t remember) and your browser won’t follow the link (unless you have javascript disabled)