MRJethva
MRJethva

Reputation: 367

cant get custom message alert in page leave "onbeforeunload" event

I put following script to prevent leave page meanwhile processing steps

<script language="JavaScript">
window.onbeforeunload = confirmExit;

function confirmExit()
{
JQObj.ajax({
    type: "POST",
    url: "<?php echo $this->url(array('controller'=>'question','action'=>'cleaSess'), 'default', true); ?>",
    success: function(data){}
});

return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

</script>

But every time i get default alert message instead of i set custom alert message,

And i want to call ajax call when end user click on "Leave page" button, but in above script ajax call calls before the click leave button,

Anyone have idea or logic to call ajax if and only if people leave the page.

Upvotes: 1

Views: 5191

Answers (2)

gkalpak
gkalpak

Reputation: 48211

You can use the "unload" event for sending the AJAX request:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "You have attempted to leave this page. "
               + "If you have made any changes to the fields without "
               + "clicking the Save button, your changes will be lost. "
               + "Are you sure you want to exit this page?";
    };

    window.onunload = function() {
        // Ending up here means that the user chose to leave
        JQObj.ajax({
            type: "POST",
            url: "http://your.url.goes/here",
            success: function() {}
        });
    };
</script>

See, also, this short demo.

Upvotes: 2

user848765
user848765

Reputation:

You shold try something like this:

window.onbeforeunload = displayConfirm;

function displayConfirm()
{
    if (confirm("You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?"))
    {
        confirmExit();
    }
}

Upvotes: -1

Related Questions