CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   How can I submit a form depending on some vars? (http://www.codingforums.com/showthread.php?t=285466)

Fedy 01-08-2013 05:21 PM

How can I submit a form depending on some vars?
 
Hi, I'm trying to submit a form depending on the result of a var, and specifically it is a window confirmation to save the form if the user is leaving the page. This is the code I tried:

Code:


var savebeforeexit = window.confirm("Are you sure?");
               
if (savebeforeexit) {
                       
  document.myform.submit();
                       
} else {

  //do nothing
}

However this does not work...

Old Pedant 01-08-2013 05:48 PM

And WHERE are you calling that code FROM?

If it is from window.onbeforeunload it will never work.

And quite frankly, window.onbeforeunload is the only reliable place to put a "now leaving the page" trap. But the most you can do there is allow the user to cancel his request to leave the page.

(I have wondered if you could make a synchronous HTTP request at that point. I think you could, but that's beginning to get pretty complex.)

Fedy 01-10-2013 08:11 AM

Yes, I am trying to call if from a window.unbeforeunload... what do you mean with a "synchronous HTTP request"?

Old Pedant 01-10-2013 07:48 PM

Synchronous AJAX. Or better named SJAX, I suppose.

Code:

    var http = new XMLHttpRequest();
    http.open( "GET", "someURLonYourSite.php?xxx=3", false );
    http.send( );

The false there says "wait for an answer".

felgall 01-10-2013 10:00 PM

Quote:

Originally Posted by Fedy (Post 1304852)
Code:


var savebeforeexit = window.confirm("Are you sure?");


confirm() gives your visitor three alternative responses in most browsers - in some browsers the third alternative is to disable JavaScript completely for the web page at that point in which case the call would never return to assign a value to savebeforeexit.

Calls to alert() confirm() and prompt() should only ever be used for debugging, they should never be used in a live web page.

Old Pedant 01-10-2013 11:04 PM

All true, Felgall, but irrelevant. You can't use confirm() in onbeforeunload anyway.


All times are GMT +1. The time now is 02:53 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.