Question

I need to prompt the user before he leaves the page, on confirmation close the tab and if not do nothing. I want to send an ajax call on onbeforeunload.

My only idea was to write handlers for both onunload and onbeforeunload like this:

window.onbeforeunload = function(){
    return 'Are you sure you want to leave?';
};
window.onunload = function(){
    $.get(
        "http://www.mysite.com/php/myhandler.php",
        { data: 1 }
    );
};

but this did not seem to work in jsFiddle

Was it helpful?

Solution

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;

OTHER TIPS

Just place em all inside onbeforeunload

window.onbeforeunload = function(){
    $.get(
        "http://www.mysite.com/php/myhandler.php",
        { data: 1 }
    );
    return 'Are you sure you want to leave?';
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top