0

I'm working on a chat application in which i want to detect and fire ajax when a user leaving a page by clicking back button or some other link or by closing the browser.

enter image description here

So please give your valuable solution how to achieve this.

Thank you all in advance.

Pradeepta
  • 458
  • 3
  • 19
  • 1
    possible duplicate of [How to send AJAX request when user leaves (closes) the page?](http://stackoverflow.com/questions/18839771/how-to-send-ajax-request-when-user-leaves-closes-the-page) – Qantas 94 Heavy Apr 07 '15 at 11:09
  • Hi i want the reason for negative feedback. – Pradeepta Apr 07 '15 at 13:33

3 Answers3

4

You cannot do that. The event window.onbeforeunload fires when the user is leaving the page, but it won't allow you to do any ajax calls.

All you can do is return a string, which will be shown to the user as a confirm dialog. If user presses Cancel, he will remain in the page, else the page will be unloaded.

return  "Are you sure, you want to leave this page?" // this is all you can do
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 2
    Ya, AFAIK, there is no reliable method to do that in a cross browser way, btw not mentioning user could turn off computer power – A. Wolff Apr 07 '15 at 11:10
2

Try this:

window.onbeforeunload = function() {
       $('body').mousemove(function() {
          $('body').unbind("mousemove");
               ajaxCall();
           });
        return "Are you sure? All work will lost! Cancel to upload the work";
};
OrMoush
  • 195
  • 1
  • 7
  • What is the purpose of binding mousemove event? – A. Wolff Apr 07 '15 at 11:12
  • In my code the purpose is to wait for the client decision. if the decision is to stay - call some ajax function. else do nothing and close the page. – OrMoush Apr 07 '15 at 11:22
  • In practice this will not work properly, as the Ajax call will not stop the browser stopping execution and closing the window, because it is meant to be asynchronous. – Qantas 94 Heavy Apr 07 '15 at 13:39
0

Try to bind on Window.onunload() event, or jquery unload if you using Jquery. Also more widely answered in this topic

Community
  • 1
  • 1
Tomcat
  • 36
  • 1
  • 4