onBeforeUnload and multiple forms - javascript

I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.

Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.

As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

Related

How can I modify the content of an HTML page after redirecting from a form using only JavaScript/HTML?

I'm learning HTML and I'm trying to do some very basic stuffs. I have my main page under index.html, a registration form under registration.html, and a script under script.js.
Index.html has the following button: <BUTTON id="login" onclick="register()">login/registration</BUTTON>
function register()
{
if (!loggedIn)
document.location.href = "registration.html";
else
{
// Page not created yet
//document.location.href = "aacount.html";
console.log("redirecting to account page");
}
In script.js, at the top, I have let loggedIn = false;.
The form's submission button looks like this: <button type="submit" class="submit" onclick="submit()"><b>Submit</b></button>
function submit(){loggedIn = true;}
Now on my main page, I have the login button. I would like it to change to an Account button so I made this:
function checkLog()
{
if (loggedIn == true)
document.getElementById("login").textContent = "Account";
else
document.getElementById("login").textContent = "Login/Registration";
}
I want my form, which has the header form class="registration_form" action="index.html" method="post" id="form" to redirect to the main page once you click submit. Since you're now logged in, I want the login/registration to swap to an account button. I don't have any backend because I haven't learned how yet. I just want to modify index.html once it loads back in by using the checkLog() function. Is there a way to do this using only HTML/JavaScript? I have seen a couple solutions using PHP, but I will only jump into it next week once I have more free time. Until then, can I make it work this way?
Just to be sure, I have tried adding onload="checkLog()" to both the entire body text and the login button to no avail. I've also found out that adding onclick="checkLog()" on the submit button in the form doesn't do anything since it executes before the action of changing web pages occur. I basically want a onclick="" that occurs after the action.
As a lot suggested in the comments, since there is no server-side to your project yet you're trying to check if the user is logged in to your website, your best bet is either cookies or LocalStorage. In this answer I will take the LocalStorage approach.
function register()
{
if (localStorage.getItem("userAuthentication") === null)
storage.setItem("userAuthentication", "userAuthentication");
document.getElementById("login").textContent = "Login/Registration";
else {
// User is logged in
// Since the user must have localStorage set up
console.log("redirecting to account page");
document.getElementById("login").textContent = "Account";
}
}
The getItem attribute returns null if the item does not exist; meaning the item hasn't been set yet. if so, we need to set LocalStorage, and change the login button text to "Login/Registration". Else, the localStorage has to be set, meaning we can can change the login button text to "Account".

Stealing the redirect URL of a button

Is it possibe to change the return URL of a button whose job is submitting a form to the server? The main deal here is that I don't have the script that controls the button, hence the word "stealing."
If you are curious about the use case, I have a Salesforce Visualforce page that has an embedded Flow in it. I want to jump out of the Flow when the user is half way through and a certain condition is met.
Assuming the button is not in an iFrame...
$('#some_button').click(function (e) {
e.preventDefault();
// Do stuff here then submit the form..
$('#some_form').submit();
});
You could also use this method for $('#some_form').submit().... You can read more about it here.

Option to redirect to 2 different places on form submission

I looked through the web on submittig forms with jquery/ajax, but I couldnt find my specific problem anywhere. I downloaded a google form and am styling / editing it (in other words, Ihave no control over the server side code and Icannot edit the form action). In the form, I have two radio butons. If one of them iis clicked, I would like the form to submit to google (so I have the results in a google spreadsheet) but I also need it to redirect to a different page (depending on which button was selected). I assume the only way to do this would be with javascript, so I trid various jquery methods, such as
$("button").submit(); but things get complicated because its a downloaded google form. Also, the target is a hidden iframe so it doesnt show the google thank you page. Does anyone have any advice as to how I would go about my problem?
*RESOLVED***
I ended up calling this onSubmit() method on the onsubmit attribute of the form:
<script>
function redirectPage(url )
{
setTimeout(function() {
window.location = url;
}, 500);
}
function submitCheck() {
//check if one of the radio buttons is checked
if(document.getElementById("group_1677476484_1").checked == true) { //
redirectPage("http://redirect1.com");
} else {
redirectPage("http://redirect2.com");
}
}
</script>
The key was adding the setTimeout in the redirectPage method, allowing the page enough time to submit the form before redirecting.

Is it possible to refresh a form only?

I have a form that when is submited it posts to a div. Ok, so I found the issue that i was getting double submissions, so i tried to apply some jquery plugins i found, but they were useless because if you double clicked fast enough I still got a double submission. From those I found i saw the best way to prevent it was with
if (this.beenSubmitted) return false;
else
this.beenSubmitted = true;
but then, I noticed that if the form needed to be sent again, the user would have to refresh the page in order to send it. In my case, I want them to be able to send again after is sent, (Im not contradicting myself, because it would be diferent content). To explain it better, this form post ideas. If you want to post 2 diferent ideas you would have to refresht he page to post. Preventing double submission would help from submitting the same idea twice if you clicked fast enough. So, what I did is that I added this "5000":
if (this.beenSubmitted) return false, 5000;
else
this.beenSubmitted = true;
So, now it refreshed my page. But im a little picky, lol. So I find it annoying that the whole page has to refresh. What if your typing and then it refreshes. I can always lower the 5000 I know, but I still find it annoying in case you start to browse the website or to zoom in, you end up refreshed.
So, my question is, is there any way to just refresh the form? or a better way to prevent double submission that actually works for this case (that ur able to submit after a few secs) ?
this is script:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
var addcontent = jQuery('#addcontent').attr('value');
if ( addcontent.replace(/\s/g,"") == "" ) return false;
if (this.beenSubmitted) return false,5000;
else
this.beenSubmitted = true;
$.ajax({
type: "POST",
url: "post.php",
data:"addcontent="+ addcontent,
success: function(){blah blah blah, ton sof code here including pagintion here, insert into a div here also, if u need this let me know.
});
</script>
Most of that I did it from asking questinos here. My Jquery and Ajax knowledge isnt the best one.
THanks for the help =}
Rate limiting to prevent malicious behavior in ExpressJS
The above link has something about putting a timer on the submit button so that you can't click it again within 3 seconds.
<script>
var submitTimer = new Collate(3000);
</script>
<form action="post" onsubmit="return submitTimer.idle();">
why don't u use the this.beenSubmitted = true approach and combine it with a timeout? for example after 5000ms u execute the timeout and set this.beenSubmitted to false.
The statement:
return false, 5000;
will always return 5000, the use of false is redundant and pointless.
To reset a form without reloading the page (which won't necessarily reset the form in some browsers), use a reset button or call the form's reset method. You can use an onreset listener to update the beenSubmitted property if the form is reset.
Multiple submission of a form has been an issue since forms were invented, it's usually dealt with at the server (if two identical requests are received, ignore the second).
Using script at the client is unreliable since you don't know what the server is doing and you have to guess whether or not the form needs to be resubmitted.

Submit two forms with one button

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

Categories

Resources