How to get a form to submit twice using Javascript - javascript

I need to submit a form to a new window and then submit slightly altered values to the same form in the original window. I have the following function to do that.
//Now lets create the page making function!
function createInternetPage() {
//Start by checking to see if the internet page has been requested.
req_int = document.getElementById("marterial_internet").checked;
if (req_int == true){
//If it has, create the internet page.
//Send the completed form to submit in a new window, creating the broadcast page.
document.getElementById("new_material").setAttribute("target","_blank");
document.forms["new_material"].submit();
//Add "(Internet)" to the current form title
var title = document.getElementById("material_title").value;
var title_new = title + " (Internet)";
title = document.getElementById("material_title").value = title_new;
//Then submit the form on the existing window to make the internet page.
document.getElementById("new_material").setAttribute("target","_self");
document.forms["new_material"].submit();
}
//If it has not been requested then just submit the normal form.
else {
//alert("NOT Checked");
document.getElementById("new_material").setAttribute("target","_self");
document.forms["new_material"].submit();
}
}
Everything work great EXCEPT that the form on the original window never gets submitted. It changes the material_title value to add " (Internet)" after it but doesn't submit the form.
Any ideas why this is and a work around to get this working?
EDIT:
When adding a setTimeout delay, see below, the same thing is happening. Everything runs except for the last form submit.
function delay() {
//Send the completed form to submit in a new window, creating the broadcast page.
document.getElementById("new_material").setAttribute("target","_blank");
document.forms["new_material"].submit();
}
function delay2(){
var title = document.getElementById("material_title").value;
var title_new = title + " (Internet)";
title = document.getElementById("material_title").value = title_new;
//Then submit the form on the existing window to make the internet page.
document.getElementById("new_material").setAttribute("target","_self");
document.forms["new_material"].submit();
}
//Now lets create the page making function!
function createInternetPage() {
//Start by checking to see if the internet page has been requested.
req_int = document.getElementById("marterial_internet").checked;
if (req_int == true){
//If it has, create the internet page.
delay()
//Add "(Internet)" to the current form title
setTimeout('delay2()',10000);
}
//If it has not been requested then just submit the normal form.
else {
//alert("NOT Checked");
document.getElementById("new_material").setAttribute("target","_self");
document.forms["new_material"].submit();
}
}

You do not give enough time for the form to do the actions. You need to break up the requests. Use a setTimeout to do the second action.
If you are submitting to the same domain, you can always use Ajax to make the first submission and not open up a new window.
Better, is have the server handle the requests and make a second submission.

Related

Reloading the page only once on a button click

I have a Load button and I am calling onclick event on that button which would refresh the page using window.location.reload() . But ,what I want is that the reload should only be called when the button is clicked for the first time . From the second click and till the HTML page is active the reload should not be called .
How can this be achieved with javascript ?Any examples would be helpful.
You could use local storage or session storage to do that. This is a modern approach that makes use of Web Storage API.
In this case, you may set a property in the storage to hold the button click and only do the refresh if it is not yet clicked.
It is possible to do it like the following snippet:
$('button').on('click', function() {
// will return null at the first call
var buttonClicked = sessionStorage.getItem('isButtonClicked');
// will only enter if the value is null (what is the case in the first call)
if (!buttonClicked) {
// set value to prevent further reloads
sessionStorage.setItem('isButtonClicked', true);
// reload the page
window.location.reload();
}
});
A more detailed example on the web storage API can be found here, if you want to know more details about it.
One way to handle this would be changing the action that onClick performs. Try taking a look here: Change onclick action with a Javascript function
You can try sending a parameter on the first reload and using that parameter change the action of the button.
Something like:
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var secondReload= getQueryVariable("secondReload");
if(!secondReload){
//if button clicked
window.location.reload();
}else{
//deactivate button
}
</script>
you need to add a disabled attribute on the button tag within the click event.
Reloading the page only once on a button click
if you're using jQuery, something like this.
$('button').on('click',function()({
... your code here
$(this).attr('disabled');
});

Javascript Calling Function In Function Not Working

I'm trying to create a very simple chat system with auto refresh and refresh on submission of new chat message from the user.
I currently have two functions - one for submitting the new message, clearing the form and refreshing the chat (using the next function) called clearchat():
function clearchat() {
var frm = document.getElementById('chatform');
document.getElementById('fullmessage').value = document.getElementById('chatmsg').value;
frm.submit(); // form is being submitted to a hidden iframe.
frm.reset();
refreshchat();
}
And then the other that refreshes the chat that should be called when clearchat() runs and is also called every 3 seconds using an interval:
function refreshchat() {
$('#qcwindow').load(document.URL + ' #qctext');
$('#chatwindow').load(document.URL + ' #chattext');
var chatwindow = document.getElementById('chatwindow');
var difference = chatwindow.scrollHeight - chatwindow.scrollTop;
if(difference < 750) {
chatwindow.scrollTop = chatwindow.scrollHeight;
}
}
This function loads the new chat information into the DIV and then keeps it scrolled to the bottom of the div unless the user has manually scrolled away from the bottom of the div.
Both functions work individually. The problem I'm having is that when the user submits a new message it does submit the form and clear the form but it does not refresh the chat. The chat still automatically refreshes every 3 seconds, though. But I'd like the new message from the user to show up instantly.
I cannot figure out for the life of me why the refreshchat() function inside the clearchat() function isn't being called.
Any help would be appreciated. Thanks.
UPDATE:
I've added console_log("refrehsed") to the refreshchat() function and it gets added to the log every time both through hitting enter manually and also the auto refresh but the div only actually updates on the auto refresh.
When you submit the form to an iframe, you should wait for the post to finish before updating the UI. You can know that the form finished submitting by listening to the load event of the iframe the form is targeting.

User is able to click a button multiple times when it should close the form after the first click

On the main page, there's a button which popups a dialog prompting the user for their username and password. When they click "Save", the credentials are validated (both JS & SQL) and the window either closes, or tells them their credentials are invalid.
I'm experiencing some weird behavior though, where I can mash the button infinitely and then the "Save" action is performed multiple times.
On the Page_Load, we attach a Javascript 'event' to the button like so:
btnSave.Attributes.Add("onClick", "return ValidateUserPasswordSignPopup('" & txtUsername.ClientID & "', '" & txtPassword.ClientID & "');")
Javascript validation:
function ValidateUserPasswordSignPopup(userTxtBox, PassTxtBox)
{
var userTextBoxctrl = document.getElementById(userTxtBox)
var PassTxtBoxctrl = document.getElementById(PassTxtBox)
if (userTextBoxctrl.value.trim() == '') {
alert("Please enter User Name.")
document.getElementById(userTxtBox).focus();
return false;
}
if (PassTxtBoxctrl.value.trim() == '')
{
alert("Please enter Password.")
document.getElementById(PassTxtBox).focus();
return false;
}
return true;
}
Button click:
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
If SaveData() Then
Response.Write("<script language = JavaScript>window.returnValue='yes';self.close();</script>")
End If
End Sub
SaveData() just creates a few objects, runs a stored procedure, creates a few more objects, then creates a DataTable which is passed to another method and is saved to the DB. Nothing too intense.
I've tried adding code in the JS method to disable the button, then at the end of the code-side click event I re-enable it, but the window seems to hang infinitely that way.
I've also tried toggling its state between the JS (re-enabling it before each return / at the end) and then re-disabling it at the start of the click event and re-enabling it again at the end of the click event, but I'm still able to click the button multiple times with this route.
Anyone have any idea what might be causing this?
EDIT My initial thought was the time it takes for the Javascript to run, as brief of a script as it is, was allowing the user to re-click the button before the postback happens to handle the click event. I completely removed the script that gets added in the Page_Load, in the first block of code above, but the behavior still happens.
The user is able to click the button multiple times due to the lag between form submission to the server and response content coming from the server.
Disable or hide the button just before return true; in ValidateUserPasswordSignPopup.
Another way:
var submittedFlag = false;
function ValidateUserPasswordSignPopup(userTxtBox, PassTxtBox)
{
if (submittedFlag)
return false;
...
submittedFlag = true;
return true;
}
Instead of using Response.Write, try registering the JavaScript using the ClientScriptManager.RegisterClientScriptBlock Method.
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If SaveData() Then
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "YourKey", _
"<script language = JavaScript>window.returnValue='yes';self.close();</script>")
End If
End Sub

Submit form when page loads using Javascript

I am designing a page for quiz contest. I need to submit the quiz when users tries to refresh page. I am using JavaScript. Plz help me..!!
function reload() {
if(localStorage.load == 1) {
localStorage.load = +0;
document.getElementById('quesform').submit();
}
set();
}
function set() {
if(!localStorage.load || localStorage.load == 0)
localStorage.load = 1;
}
I used this code, but it didn't works in chrome. It executes the coding after submitting the form. It sets value to 1 and redirect immediately before displaying question page..
I have removed my previous answer because it is not possible to submit a form when the user tries to leave the page.
You are limited to giving the user the choice of leaving/staying.
The only solution would be to set a cookie containing the form data, so that when the user next visits your page, the data can be retrieved and submitted.

Firefox submitting form even in the case of alerts

We have a requirement that if a user clicks on any link, he should not be able to click on any other link.to achieve this, we have written a java script with incrementing counter.In case , if a user has already clicked on any link we are showing a alert box with some message.On IE its working fine, In Firefox , I am getting the alert for second click but firefox does not stop the processing of first request and refreshes the page even if alert box is untouched.
We are submitting the forms through explicit java scripts.
Hi All PFB the snippets
<script>
var counter = 0;
function incrementCount(){
if(counter>0){
alert('Your request already in progress. Please wait.');
return false;
}else{
counter=counter+1;
return true;
}
}
</script>
Form submission script:
<script>
function fnTest() {
if(incrementCount()){
document.FormName.method = "POST";
document.FormName.action = "SomeURL";
document.FormName.submit();
}else{
return false;
}
}
</script>
Link through which we are submitting the form
<span>Test</span>
Your question is unclear. If a user clicks on a submit button he should not be able to click a link? You'll need to post your code.
With regards to the form post my guess is you didn't return false onsubmit
"On IE its working fine, In Firefox ,
I am getting the alert for second
click but firefox does not stop the
processing of first request and
refreshes the page even if alert box
is untouched"
Well, what's wrong. Firefox is submitting the first request as you want and it shows an alert on the second click. How is IE different? Is FF doing a double submit?
PS: You dont really need to use a counter. Use this code :
var handlers = {
alert : function(){
alert('Your request is already in progress. Please wait.')
return false
},
submitForm : function(){
this.onclick = handlers.alert //this refers to the a tag
document.FormName.submit()
}
}
document.getElementById('mysubmitlink').onclick = handlers.submitForm
And on your link becomes:
`<span>Test</span>`
You can allways return false on your onsubmit call.

Categories

Resources