2

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.

Wazy
  • 8,822
  • 10
  • 53
  • 98

4 Answers4

8

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?

Community
  • 1
  • 1
Anthony
  • 81
  • 1
  • 2
4

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.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
3

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 !

Aelios
  • 11,849
  • 2
  • 36
  • 54
2

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

$(document).ready(function() {
  window.onbeforeunload  = saveBeforeExit;
});
sinner73
  • 157
  • 8