You can't do that. There's no way in modern browsers to reliably do a non instant operation on the beforeunload
event (especially, all operations involving a query are usually prevented). It's a security measure : nothing that may delay or prevent the user-required closing of a window is acceptable.
You need to change the logic of your application. Modern AJAX applications must continuously save the data that need saving or provide a visible way to launch the save, they can't wait for the window to be closing. And you have to manage your sessions life-cycle server-side without relying on the browser issuing a log-off.
Regarding the alert and Chrome, here's an extract from the MDN :
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog(), window.alert(), window.confirm(), and
window.prompt() methods may be ignored during this event.
It's probable that more and more browsers will prevent this alert which is just painful most of the times.