My code is like this:
window.onbeforeunload = function() {
$.post('ajax_url',$('form').serialize());
return "are you sure";
}
Now I want to send an ajax request if window is closed, but not when he stayed on the page by clicking cancel button.
move your ajax to an unload event handler