0

i am using ajax and jquery to send an *synchonou*s http request to a php script in a web aplication to log out the user if incase the user decides to leave the page rather than logout.

i am using hte following code:

function close()
{
  return "If you exit you will be logged out ...!";
}
window.onbeforeunload = close;

$(window).unload( function () { 

$.ajax({
        url: "logout.php",
        async:false,
        success: function(msg){
        alert( "You have been logged out ...!");}
});     
});

the ajax is working in ALL cases apart from when i press the back button. When i press the back button i even get the success function running but when i check the php script has not run as i have a fwrite function in it to tell me it worked. it is working in other cases apart from the back button.

user434885
  • 1,988
  • 6
  • 29
  • 51

1 Answers1

2

i am using ajax and jquery to send an asynchonous http request

The request in the code you've quoted is synchronous, not asynchronous.

If you're seeing the success function get called when you're not seeing the PHP code running, that means your browser has cached the previous result and reused it. You may be able to bypass that by adding cache: false to your request options.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • i just tried adding the cache: false, it did not work. can it have anythign to do with the fact that when i press back it heads back to another php script ? – user434885 Apr 14 '11 at 09:06
  • @user: If you're really seeing the `success` function get called, but you're really *not* seeing the logged line from your PHP, I can't see any other option than that the browser used a cached response or (apologies) that you're mis-observing. Regardless, doing anything on page unload is *extremely* unreliable (that code won't do what you want on Safari, Opera, IE9, prob. others), so I assume you must have a fallback in place (time-out, etc.). I would recommend not having the `alert` and simply taking any proactive logout you get from the unload as a *bonus*, not anything you actually rely on. – T.J. Crowder Apr 14 '11 at 09:33