33

I have this little piece of code:

<script>
$(window).bind('beforeunload', function() {
  $.ajax({
    async: false,
    type: 'POST',
    url: '/something'
    });
  });
</script>

I wonder, how could I disable this request when user hits the submit button.

Basically something like here, on SO. When your asking a question and decide to close the page, you get a warning window, but that doesn't happen when you're submitting the form.

pawelmysior
  • 3,190
  • 3
  • 28
  • 37

7 Answers7

47

Call unbind using the beforeunload event handler:

$('form#someForm').submit(function() {
   $(window).unbind('beforeunload');
});

To prevent the form from being submitted, add the following line:

   return false;
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • 4
    add the following line: `return false;`, but where I add that line? – Kiquenet Oct 24 '17 at 08:30
  • $(window).unbind('beforeunload'); throws error to me as stated below Uncaught SyntaxError: Unexpected token '.' but binding works well as below $(window).bind('beforeunload', function(){return 'Are you sure you want to leave?';}); – Jeet May 08 '20 at 14:42
20

Use

$('form').submit(function () {
    window.onbeforeunload = null;
});

Make sure you have this before you main submit function! (if any)

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Parham
  • 1,037
  • 11
  • 17
0

This is what we use:

On the document ready we call the beforeunload function.

$(document).ready(function(){
    $(window).bind("beforeunload", function(){ return(false); });
});

Before any submit or location.reload we unbind the variable.

$(window).unbind('beforeunload');
formXXX.submit();

$(window).unbind("beforeunload"); 
location.reload(true);
David
  • 362
  • 2
  • 7
0

Looking for Detect onbeforeunload for ASP.NET web application well I was, I've to show warning message if some input control changes on the page using ASP.NET with Master Page and Content Pages. I'm using 3 content placeholders on the master page and the last one is after the form

<form runat="server" id="myForm">

so after the form closing tag and before the body closing tag used this script

<script>
        var warnMessage = "Save your unsaved changes before leaving this page!";
        $("input").change(function () {
            window.onbeforeunload = function () {
                return 'You have unsaved changes on this page!';
            }
        });
        $("select").change(function () {
            window.onbeforeunload = function () {
                return 'You have unsaved changes on this page!';
            }
        });
        $(function () {
            $('button[type=submit]').click(function (e) {
                window.onbeforeunload = null;
            });
        });
    </script>

beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively

so I got it working like this bind and unbind didn't work out for me also With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions.

dnxit
  • 7,118
  • 2
  • 30
  • 34
0
 <!DOCTYPE html>
 <html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>
  <script type="text/javascript">
    $(function() {
        $('#form_verify').dirtyForms();
    })
  </script>
  <title></title>
 <body>
<form id="form_verify" action="a.php" method="POST">
    Firt Name <input type="text">
    Last Name <input type="file">
    <input type="submit">   
</form>

Anup Panwar
  • 293
  • 4
  • 11
0

if you're using bind then use this:

$('form').submit(function () {
    $(window).unbind('beforeunload');
});

This will be good for all form submit.

ShelðÔn Alag
  • 367
  • 2
  • 3
  • 12
0

Super old question but might be useful to others.

Simply detaching the "beforeunload" from the "submit" event would not work for me - because the submit handler was being called even when there were errors in the form that the user had to fix. So if a user attempted to submit the form, then received the errors, then clicked to another page, they would be able to leave without the warning.

Here's my workaround that seems to work pretty well.

(function($) {

    var attached = false,
        allowed = false;

    // catch any input field change events bubbling up from the form
    $("form").on("change", function () {
        // attach the listener once
        if (!attached) {
            $("body").on("click", function (e) {
                // check that the click came from inside the form
                // if it did - set flag to allow leaving the page
                // otherwise - hit them with the warning
                allowed = $(e.target).parents("form").length != 0;
            });

            window.addEventListener('beforeunload', function (event) {
                // only allow if submit was called 
                if (!allowed) {
                    event.preventDefault();
                    event.returnValue = 'You have unsaved changes.';
                }

            });
        }                
        attached = true;
    });

}(jQuery));

This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning. If the click to leave the page originated from outside of the form, then it will warn the user.

Jon Freynik
  • 359
  • 2
  • 15