It works fine in this fiddle--> Perfectly working fiddle!!!
function warning(){
if(true){
return "You are leaving the page";
$.ajax({
url: "test.php",
type: "post",
data: values to send
})
}
}
window.onbeforeunload = warning;