You can use window.onunload to fire an AJAX call when the user leaves the page/closes the tab.
window.onunload = function(){
  // AJAX call to mark user "offline"
}
EDIT: I suggest setting a variable when clicking on links, so that this only runs when the user leaves the page.
Using jQuery, it can be done like this:
$('a').click(function(){ // Run for all links
  $('body').data('linkClicked', true); // Set global variable
});
$(window).unload(function(){ // jQuery version of window.onunload
   if(!$('body').data('linkClicked')){ // Check global variable
      $.ajax({
        url: 'url',
        data: {some: data},
        async: false // this locks the browser, but it may be needed to make
                     // sure the ajax call runs before the tab is closed
      });
   }
});