Submit form when page loads using Javascript - 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.

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".

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.

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.

Reset inputs in the previous form for a Jquery Mobile Multi Page Application

I developed an application using Jquery Mobile with multi pages (each one has an individual form) in a single html file.
And I haven't figure out until now how I can clear all fields of a previous form when the
button Back (type data-rel="back" located on page header) is pressed, and the previous form is showed.
My flow is similar as described bellow:
Show page Login
On Login page fill fields (user, password), validate the form and submit it.
After submit, change page for second page (Same HTML, data-role="page" )
After press Back Button on the second page (not browser), the Login page
still showing all input fields filled.
I saw a lot of snippets but not in particular related with this issue and when I tried
to apply some of them I didn't get the clue to solve this.
Someone could help, please. Thanks!
If you want to clear the fields each time the form is visited you can simply use the pagebeforeshow event:
$('#page1').on('pagebeforeshow', function (event, data) {
//clear fields here
});
If you only want to clear the fields when coming back from the second page, the same event has a second argument which tells you where you are coming from.
$('#page1').on('pagebeforeshow', function (event, data) {
var prevPageID = $(data.prevPage).attr("id");
if (prevPageID == "page2"){
//clear fields
}
});
API doc can be found here: http://api.jquerymobile.com/pagebeforeshow/

How to get a form to submit twice using 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.

Categories

Resources