Here is one way to do it:
Note that the request probably has to be synchronous (call request.open with async=false).
One additional notable point of attention:
If the client is terminated abruptly (e.g., browser is closed with "End Process" or "Power Down"), then neither the onunload event nor the onbeforeunload will be triggered, and the request will not be sent to the server.