I'm using jQuery to show a confirmation message for the user when leaving the page as follows:
var changes = false;
window.onunload =function() {
if (changes) {
$.post("check.php",{undovideokey:VID});
} else return null;
};
on the other hand
<input type='submit' name='Add' value='submit ' align='right' onclick="changes = true;" />
A problem occurs when running the code in Google Chrome when I refresh the page. I have seen many problems like this but there is not helpful answers.
jQuery ajax call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?
window.onbeforeunload ajax request in Chrome
thanks,
Sara
If I understand correctly, your issue that the AJAX request occurs after the page has been refreshed.
Changing the code to trigger on the onbeforeunload
event and using a synchronous AJAX request should fix your problem:
var changes = false;
window.onbeforeunload = function() {
if (changes) {
$.ajax({
async: false,
url: "check.php",
data: {
undovideokey: 'foo'
}
});
} else {
return null;
};
};
Note that this is difficult to see in Chrome's developer tools, since it does not persist AJAX requests across reloads. You should verify the behaviour on the server-side or by using a tool like Fiddler
Working demo: http://jsfiddle.net/wq4hk/4/show (Editable via http://jsfiddle.net/wq4hk/4/)
I've noticed browsers will attempt to maintain to some extent javascript state whenever you click the "refresh" button or press F5 (or whatever the heck it is on a mac). When you're developing it's a really annoying feature because you want to start from a fresh state. This may seem dumb but something I do to force a fresh state is to place my cursor in the address box and hit enter. Chrome will then treat it as I'm starting a new session and not hold any lingering javascript state. I've run into a lot of quirky behavior when just pressing F5 for code that depends on having a clean state and fresh events.