0

Is calling an ajax function possible before someone's decide to leave the page. I mean i can ask the user if user wants to leave or stay. But i dont know how to alter behaviour when user click "yes leave the page" button.

I have this code working..

<head> <script type="text/javascript"> function catchExit() { return "All your data is going to be lost. Are you sure??"; } </script> </head> <body onbeforeunload="return catchExit()"> <p> Dont leave the page. </p> </body> 
1
  • 3
    Short answer is that you can't. If they chose yes, they're off and running. You could impose a confirm before it defaults to browser behavior though. Commented Aug 18, 2012 at 12:49

2 Answers 2

1

Here's an alternative way using confirm:

function catchExit(){ var exit = confirm("Are you sure?"); if (exit){ } } 

But keep in mind that AJAX can't stop the thread. That means that there's no guarantee the call:

  1. Makes it
  2. Is successful
  3. Returned a result

The window will have shown the prompt and/or exited before the AJAX may have even completed. To illustrate it better:

function catchExit(){ $.ajax({ success: function(){ // this is an entirely new thread and returning a result // has ZERO effect on the original catchExit function // (And chances are it's already executed and is long gone) } }); // this (99.99% of the time) will be called long before // 'success' above is called, therefore making 'success' and its // outcome moot. return "There are unsaved changes, are you sure you want to exit?"; } 
Sign up to request clarification or add additional context in comments.

1 Comment

What if it was a synchronous request?
0

Actually, i found a way to get my $.ajax() call worked. Setting async parameter to false works in firefox, chrome, iexplorer and safari. It only doesn't work in opera.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.