0
window.onbeforeunload( function() { 
      return "Are you sure?" ;
});

I want to perform an an AJAX call before the page being unloaded, Is there any other way to achieve this, coz this doesn't work? Awaiting, thankss :)

2 Answers2

0

Try this instead :

window.onpagehide(function() {
    return "Are you sure?";
}

Hope this will help !!

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
0

If you want to run a function as the page is unloading, you can try $(window).unload(), but it can't stop the page from unloading or redirect the user. Also, some browsers block alerts in unload.

$(window).unload(function(){
  $.ajax({url:"http://localhost:80/ajax.php?", async:false});
  alert('Bye.');
});

But your best bet is to do something like:

$(window).bind('beforeunload', function(){
   $.ajax({url:"http://localhost:80/ajax.php?", async:false});
  return 'Are you sure you want to leave?';
});

//I tested this in IE9, Chrome, and Firefox and the ajax call fired successfully each time.

JSFiddle example

Also if you're doing an ajax request on page unload try setting async to false:

$.ajax({url:"http://localhost:80/ajax.php?", async:false});
Jack
  • 1,319
  • 8
  • 16