You can use websockets for that (nodejs example):
socket.on('disconnect', function(){
// do server stuff here
});
You are not guaranteed to handle this from client side, because user can simply close browser. another way is to use ajax to notify server "hey i'm online" with interval of time. if server stops receiving notification, that means user went offline (websockets are better way)