title: jQuery: Click tracking with PHP
body: <p>Yes, I KNOW about Google Analytics. We use it for our overall site metrics, and I know we can track individual links.  However, we needed a tracking solution for very specific links and we need that tracking data available to our web application <em>in real time</em>, so I wrote my own solution:</p>
  
  <p>jQuery:</p>
  
  <pre><code>  $.fn.track = function () {
      var source, url, name, ref, $this;
      $this = $(this);
      if (window.location.search.substring(1) != '') {
        source = window.location.pathname + "?" + window.location.search.substring(1);
      } else {
        source = window.location.pathname;
      }
      url = jQuery.URLEncode($this.attr('href'));
      name = $this.attr('name');
      ref = jQuery.URLEncode(source);
      $this.live('click', function (click) {
        click.preventDefault();
        $.post('/lib/track.php', {
          url: url,
          name: name,
          ref: ref
        }, function () { window.location = $this.attr('href'); });
      });
    };
  </code></pre>
  
  <p>... using the jQuery URLEncode plugin (<a href="http://www.digitalbart.com/jquery-and-urlencode/" rel="noreferrer">http://www.digitalbart.com/jquery-and-urlencode/</a>).</p>
  
  <p>Now, this code works fine with my PHP backend and on my machine, but it doesn't seem to work reliably for everyone else.  Sometimes the parameters passed in via jQuery are NOT passed in, resulting in a record in the database with no <code>name</code>, <code>url</code> or <code>ref</code>.</p>
  
  <p>For the life of me, I can't figure out why this might be happening; I know the <code>$.post</code> is triggering, since there are records in the database (in the PHP, I also record the IP of the request along with the timestamp), but in many cases the PHP script is receiving blank <code>$_POST</code> variables from jQuery.  </p>
  
  <p>I've tested it live on every browser I have access to at my workplace, and all of them work fine for me; however, about 75% of all the records created (not by my computers) come through as blank (most of them are using the same browsers I am). </p>
  
  <p>Why could this be happening?</p>