Вопрос

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

Это было полезно?

Решение

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;

Другие советы

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?';
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top