3

In my MVC application, when a user leaves a certain page I need to prompt them with a warning like so:

    $(window).on("beforeunload", function () {
         return "You will lose changes, are you sure?"
    });

This jquery works, but first I need to check whether the user should be warned in the first place. This check is complex and needs to be performed server side (I've struggled to find an example of this). Is it possible?

I've tried an ajax post:

$(window).on("beforeunload", function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("SaveCheck")",
        async: false
        success: function (result) {
            //return a string here if saving required
        }
    });
});

But this doesn't work like above - the "beforeunload" function already returns and doesn't care about the result of the ajax post.

Is there some way I can use a calculated flag from the server to check whether the user should be warned or not before they exit?

This answer looks relevant, but does not allow you to use the result of the ajax call in the "beforeunload" function, therefore you can't warn the user: window.onbeforeunload ajax request in Chrome

Community
  • 1
  • 1
FBryant87
  • 4,273
  • 2
  • 44
  • 72
  • 2
    You probably need to wait for the promise returned by the ajax call to complete. See this answer: http://stackoverflow.com/questions/16814416/jquery-promise-wait-to-ajax-end – Pelle Oct 26 '16 at 11:36
  • @Pelle That promise technique worked great thanks! If you want to add an answer I'll accept it to give you rep. – FBryant87 Oct 26 '16 at 12:22
  • Great! I added my answer. – Pelle Oct 26 '16 at 13:00

1 Answers1

2

You probably need to wait for the promise returned by the ajax call to complete. See this answer: Jquery promise wait to ajax end

Community
  • 1
  • 1
Pelle
  • 2,755
  • 7
  • 42
  • 49