Your best bet would be to use window.onbeforeunload, an event which is fired when the window is about to unload its resources.
window.onbeforeunload = function(){
// Ajax request to update db here
}
However, this has a couple of drawbacks: the event will fire if the user refreshes the page and the AJAX request is not guaranteed to ever reach the server.
A more reliable way to do this might be to have a relatively short session timeout on the server side (e.g. 1 minute) and introduce an AJAX based heartbeat on the client side (e.g. every 30 seconds) to keep the session alive.