Wasim Karani
Wasim Karani

Reputation: 8886

jQuery.ajax on onbeforeunload event not working

I have one php page like this

<script type="text/javascript" src="js/jquery.min.js"></script> 
<script type="text/javascript">
window.onbeforeunload  = saveBeforeExit;
function saveBeforeExit() {  
    jQuery.ajax({
        url:"truncate_logs.php",
        type:"GET",
        async:false,
        success:function(data){

        }
    })
}
</script>

//I am creating 'logs_".$t.".xls' here

<?php
header("Location: log_files/logs_".$t.".xls");
?>

My problem is here on

Location:onbeforeunload is not getting called.

Upvotes: 2

Views: 8948

Answers (4)

Aelios
Aelios

Reputation: 12137

I had the same problem and solved it with :

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox
    if (e) {
        e.returnValue = '';
    }

    // For Chrome and Safari
    return '';
};

However Opera does not seem to catch onbeforeunload event, so bad !

Upvotes: 3

sinner73
sinner73

Reputation: 167

Your assign to the event probably comes too early (page not ready).
Please try:

$(document).ready(function() {
  window.onbeforeunload  = saveBeforeExit;
});

Upvotes: 2

Anthony
Anthony

Reputation: 81

I found the answer. Add async : false to your jquery ajax request.

See How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Upvotes: 8

kgiannakakis
kgiannakakis

Reputation: 104178

onbeforeunload is not working because it isn't coded properly. You need to return a string from onbeforeunload , which will be used as the message in the window that will appear.

Upvotes: 4

Related Questions