Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 357
pawelmysior Avatar asked Jan 24 '11 22:01

pawelmysior


People also ask

How do I cancel a Beforeunload event?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.

What is Beforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


2 Answers

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; 
like image 173
Jacob Relkin Avatar answered Oct 02 '22 18:10

Jacob Relkin


Use

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

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

like image 37
Parham Avatar answered Oct 02 '22 20:10

Parham