0

I want to post data before unload (just before visitor closes page). Unload may vary on different browsers, so I have done this following script;

$(document).ready(function(){

var runme = true;

$(window).bind('beforeunload', function () {
    if(runme){

if ($("#benyaziyormuyum").val()=="evet") {

$.post("yazmabirak.php", {
karsidaki: "exited",
});

}
        runme=false;
    }

});

$(window).unload(function () {
    if(runme){

$.post("yazmabirak.php", {
karsidaki: "exited",
});
        runme=false;
    }
});

It works on all browsers, except Chrome. My question is, which before unload function should be used to make it work on Chrome ?

user198989
  • 4,574
  • 19
  • 66
  • 95

1 Answers1

2

Are you sure it isn't getting called?

$.post is an asynchronous call and you have nothing that prevents the browser from continuing on after the $.post().

You need to make this synchronous by using $.ajax() where you can set async: false

how to make a jquery "$.post" request synchronous

http://api.jquery.com/jquery.ajax/

Community
  • 1
  • 1
Dave Bush
  • 2,382
  • 15
  • 12
  • Nope, suprisingly if you close the chrome windows, it doesnt work. But if you go another page (without close) it works. – user198989 Feb 06 '16 at 03:40
  • So you set a break point, closed the window, and never hit the breakpoint. I've used before unload multiple times to prevent closing the window and it always works for me. I still thing your problem is one of syncronicity – Dave Bush Feb 06 '16 at 11:22
  • Maybe thats Chrome's bug. If you add alert(); it may work, but there is a problem when sending post before visitor close the window. Did your script also posts ? – user198989 Feb 07 '16 at 00:52