2

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

1
  • So, what exactly is the problem? I don't see a question in your post. Commented Apr 26, 2011 at 21:04

2 Answers 2

2

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/)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

+1 for not knowing how to refresh a mac. i didn't know for the longest time, but apparently it's the apple key + R

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.