Search code examples
javascriptjqueryajaxonbeforeunload

How to disable beforeunload action when user is submitting a form?


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.


Solution

  • 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;