0

I am using following code on a html page

window.onbeforeunload = function() {  
    return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your
    unsaved changes";    }

when a user try to leave the current page the i ask the user a confirmation either he/she want to leave the page or not. there are two button 'leave the page' and 'cancle'

How can i know if user click on the leave button then i have to send a ajax request (that ajax request do some action in DB) .

Thanks in advance.

Ahsan aslam
  • 1,149
  • 2
  • 16
  • 35

2 Answers2

0

DEMO

window.onunload=callajax;

function callajax() {
   /*Your ajax call code*/
   return "ajax response";//returning ajax response
}

You can use like this also:

window.onbeforeunload = callajax;
function callajax() {
   /*Your ajax call code*/
   return "ajax response";//returning ajax response
}
Community
  • 1
  • 1
Manwal
  • 23,450
  • 12
  • 63
  • 93
  • it is not working..i am using following code ``window.onbeforeunload =callajax; function callajax() { $.post( "test.php", function( data ) {}); return "ajax response";//returning ajax response }`` the ajax call also execute when i click on the cancle.. i want to send ajax on leave button call – Ahsan aslam Sep 24 '14 at 07:08
0

window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

Please take a look at this link , it is exactly what you are asking for . The trick is to use synchronous ajax in your function for window.onunload :

window.onunload=function(){
xmlhttp.open("GET","/YourAction",false);
}

The above function will be called when the user presses the "leave the page" button , and since the ajax request would be synchronous , the document would only unload completely when the ajax request finishes.

Community
  • 1
  • 1
  • it is not working i am using following code ``window.onbeforeunload = function () { return "Are you sure want to leave this page ?"; }; window.onunload = function () { xmlhttp.open("GET","test.php",false); };`` – Ahsan aslam Sep 24 '14 at 07:15