0

My code is like this:

window.onbeforeunload = function() {
    $.post('ajax_url',$('form').serialize());
    return "are you sure";
}

Now I want to send an ajax request if window is closed, but not when he stayed on the page by clicking cancel button.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tachyons
  • 2,131
  • 1
  • 21
  • 35

2 Answers2

1

move your ajax to an unload event handler

window.onunload = function() {
   $.post('ajax_url',$('form').serialize());
}
Keith A
  • 771
  • 6
  • 12
0

Answer taken from this post.

In your case you might do something like this:

setTimeout(function() {
   setTimeout(function() {
        $.post('ajax_url',$('form').serialize());
   }, 1000);
},1);
return 'are you sure';

The code within the first setTimeout method has a delay of 1ms.
This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog.

This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed.

If the user pressed cancel, it will trigger another setTimeout which fires in about one second.
If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

Community
  • 1
  • 1
Jai
  • 74,255
  • 12
  • 74
  • 103
  • Thanks , But I want to send the request when window is closed , not when cancel button is pressed :-) – Tachyons Jun 18 '15 at 10:09