Redirecting after submit with counter - javascript

I am trying to redirect with counter to another page. I want the redirect to start when I have submit the form. I want to redirect to another page after submit form.
var count = 6;
var redirect = "https://www.google.com";
function countDown() {
var timer = document.getElementById("timer");
if (count > 0) {
count--;
timer.innerHTML = "This page will redirect in " + count + " seconds.";
setTimeout("countDown()", 1000);
} else {
window.location.href = redirect;
}
}
<form method="post">
<p>
<label>Name
<input type="text" name="textfield">
</label>
</p>
<p>
<input type="submit" name="Submit" value="Submit"><br>
</form>
<span id="timer">
<script type="text/javascript">countDown();</script>
</span>
</p>

A form submit is always a request to the server. You can either use ajax to perform the submission of the form or you can just count and submit the form afterwards.
To prevent your form from submitting when a user hits the button u can prevent the default behaviour like so:
$('input [type=submit]').on('click', function( event ) {
event.preventDefault();
// use your counter here
// when counter hits 0 just submit the form with
$('form').submit();
});
or use an ajax call:
$('form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: 'url/to/form/action',
data: $(this).serialize(),
method: "POST",
success: function() {
// start your counter
// REDIRECT
}
});
});
The Problem with the first method would be that you are just delaying the form submission.
In the second case u cant reliably tell when you will get an success (or error) response since the call is asynchrous. This will result in either a delay before your counter starts or a possible delay after your counter ends if the server didnt respond until then.

You can achieve a counter by using setInterval, and making a check until it hits 0 to redirect:
<form method="post">
<p>
<label>Name
<input type="text" name="textfield">
</label>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
<br>
</form>
<span id="timer">This page will redirect in <span id="count"></span> second(s).</span>
<script type="text/javascript">
var count = 6;
var redirect = "https://www.google.com";
var elem = document.getElementById('count');
elem.innerText = count
setInterval(() => {
count--
elem.innerText = count
if (count == 0) {
window.location.href = redirect;
}
}, 1000)
</script>

Related

SetInterval does not run from HTML form's onClick event

I just wrote a timer function that does count down from 5 seconds on the page. Next I wanted to create a form that would call the timer function when submitted.
But even though the onClick triggers the function (and console logs "hi"), it never executes setInterval.
Is there a reason why setInterval works when I call the function immediately, but not when I submit the form? After some research, I still can't work out the reason for this.
<body>
<h1 id="title">
This a simple timer
<form action="">
<input type="text" name="duration" />
<input type="submit" onclick="timer()" />
</form>
</h1>
<script src="src/index.js"></script>
</body>
javascript
const title = document.getElementById("title");
const btn = document.getElementById("btn");
const timer = () => {
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
};
Since HTML forms with action attribute set to empty string submit their form to the current page, you are reloading your page every time you submit since why your JS function never gets called
what you can do is prevent default(reload) behavior by calling e.preventDefault() before your console.log("hi"); statement.
and your <input type="submit"... would change to <input type="submit" onclick="timer(event)" />
also don't forget to add the parameter to const timer = e => {...
Submitting a form in html means that the URL specified with action will be loaded with the data from you form. If you set action to an empty string, the current page is reloaded with the form's data. So in your case you are reloading your page everytime you click the submit button.
If you just want to start the timer with a button, you don't need a form and you don't need an input of type submit. Use
<body>
<h1 id="title">
This a simple timer
</h1>
<input type="text" name="duration" />
<input type="button" onclick="timer()" value="click me!" />
<script src="src/index.js"></script>
</body>
Also, you shouldn't put anything in your <h1> apart from the actual text of your title.
I see two problems here. Your html structure. You should try this instead. I added “event” so I could target the input element. But you could also give the form tag a name or set an I’d to target it directly when the submit button gets clicked.
<body>
<h1 id="title"> This a simple timer </h1>
<form action="">
<input type="text" name="duration" />
<input type="submit" onclick="timer(event)"/>
</form>
<script src="src/index.js"></script>
</body>
Previously when the onclick event triggers you update the DOM by replacing the text contents in #title and that tag wraps the form also. I think you should make them independent. And 2, the page gets reloaded so you should handle the page submission by using preventDefault(); on the form. see example below
const title = document.getElementById("title");
const btn = document.getElementById("btn");
const timer = e => {
e.preventDefault();
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
};
Here is another approach, i adjusted the html and javascript.
No onclick event
<h1 id="title"> This a simple timer </h1>
<form action="" name="simple_timer">
<input type="text" name="duration" />
<input type="submit"/>
</form>
We just set a form name.
Javascript set to listen for any submission by that form then prevents it from occuring.
const title = document.getElementById("title");
const timer = document.forms['simple_timer'];
timer.addEventListener('submit', (e) => {
e.preventDefault();
console.log("hi");
let interval = 5;
let countdown = window.setInterval(() => {
title.innerText = "00:" + interval;
interval--;
if (interval === 0) {
title.innerText = "DONE";
clearInterval(countdown);
}
}, 1000);
});
Guess that’s all.

how can i make my submit button clickable once and still execute my php?

I have tried solving this but no matter what i try the button doesn't stay disabled for more than a second and won't execute my PHP script.
I have a restart button on my web page that when clicked sends an email to the admin to let them know a restart has been requested. I want this to be able to be clicked once then become greyed out to prevent multiple clicks. I want it to become active again after a certain amount of time
How can I get the Restart button to become clickable once (to rule out the possibility for too many script executions) and still execute the PHP script?
This is my code:
<form action=index.php method= "post">
<input type="submit" value="Request Restart" id="alertTimerButton" name="clickMe" onclick="countClicks();"/>
<?php
if (isset($_POST['clickMe']))
{
exec("/anaconda3/bin/python /Users/shoot_station_5/Sites/simpleblogs/restartemail.py \"$input_val\"");
} else{
}
I have tried adding various javascript such as:
function disable()
$(document).ready(function(){
$('.once-only').submit(function(){
$(this).children('button').prop('disabled', true);
alert("Thankyou a restart has been requested.");
});
});
and
<script type="text/javascript">
var ClickCount = 0;
function countClicks() {
var clickLimit = 1; //Max number of clicks
if(ClickCount>=clickLimit) {
alert("a restart has already been requested");
return false;
}
else
{
ClickCount++;
alert("Thankyou a restart has been requested.");
return true;
}
}
You have to change
onclick="countClicks();"
to
onclick="return countClicks();"
then your 2. solution does work.
Your 1. solution has multiple bugs. Don't wrap the code in a disable() function. And there is a # missing before 'button'.
I would do it like this:
onclick="disabled=true;"
That's enough.
Because you commented that you don't get your second solution running, here is the code:
var ClickCount = 0;
function countClicks()
{
var clickLimit = 1; //Max number of clicks
if (ClickCount >= clickLimit)
{
alert("a restart has already been requested");
return false;
}
else
{
ClickCount++;
alert("Thank you a restart has been requested.");
return true;
}
}
<form action="#" method="post">
<input type="button" value="Request Restart" id="alertTimerButton" name="clickMe" onclick="return countClicks();"/>
</form>
Well the button is working as intended. Since you don't use ajax/xhr here you reload your page when the form is submitted. That's why the button is resetted. If you don't want to use ajax/xhr just save your "status" and maybe the time in a session variable and change the button property according to it. Your html/php would look like this
session_start();
if (isset($_POST['clickMe'])) {
$_SESSION['restarted'] = time();
}
session_write_close();
$timeout = 300; // 5 min
$timer = time();
$disabled = false;
if (isset($_SESSION['restarted']) && ($timer - $_SESSION['restarted']) < $timeout) {
$disabled = true;
}
.. (html stuff) ...
<form action=test.php method= "post">
<input type="hidden" name="timer" value="<?php echo (isset($_SESSION['restarted']) ? $_SESSION['restarted'] : null)?>" />
<input type="submit" <?php echo ($disabled ? 'disabled="true"' : null)?> value="Request Restart" id="alertTimerButton" name="clickMe"/>
</form>
And your js like this (if you use jquery)
$(document).ready(function(){
$('form').on('submit', function(e){
alert("Thankyou a restart has been requested.");
return true;
});
var restart_time = parseInt($('input[name="timer"]').val());
var cur_time;
setInterval(function(){
cur_time = Math.floor(Date.now() / 1000);
if (cur_time - restart_time > 300000) {
$('#alertTimerButton').prop('disabled', false);
}
}, 5000);
});
Edit: I fixed the code a bit and added a time check in javascript.

Form Validation in a pop up window

Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.

jQuery disable form submit in less than xx seconds

I have a user registration form.I need to check if user form filled in less than xx seconds(5 seconds). If less than 5 seconds disable the form submit. Some thing like that disable the submit button click or return false or like that.
I wrote some jquery scripts.But not correctly working.
Here is the sample form.
<form id="registerform" class="registerform" method="post"/>
<input type="text" name="username" id="username" />
<input type="text" name="email" id="email" />
<input type="submit" name="submit" id="submitBtn" value="Submit" />
</form>
Here is the jquery scripts.
<script type=javascript>
jQuery.noConflict();
jQuery(document).ready(function ($) {
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var checktime = 0;
jQuery('form#registerform').find(':input').each(function(){
jQuery(this).keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
jQuery(this).keydown(function(){
clearTimeout(typingTimer);
});
});
function doneTyping () {
checktime = typingTimer;
return checktime;
}
jQuery('form#registerform').submit(function() {
checktime = doneTyping ();
var timerInsec = (doneTypingInterval/1000);
if(checktime < timerInsec) {
return false; // disable form submit
} else {
// if user take to fill the form more than 5 seconds, submit the form
return true;
}
});
});
</script>
I need to integrate to the wordpress registration form.That's why I tried.
If anyone have a solution/solutions to this please help me. Really appreciate that.
Thank you
This will disable your submit button for 5 seconds:
var submitButton = $('#submitBtn');
submitButton.prop("disabled", true);
setTimeout(function() {
submitButton.prop("disabled", false);
}, 5000);
Online example
You would also want to make sure, that the malicious user doesn't submit the form by other means! Make sure to run server-side validation:
if ( isset($_SESSION['last_submit_time']) ) {
$delay = intval($_SESSION['last_submit_time']) + 5;
if ( time() < $delay ) {
$_SESSION['last_submit_time'] = time();
echo "You must wait for 5 more seconds before submitting. Timer reset.";
exit;
}
}
typing timer does not contain the time , instead it contains an id for the timer thats currently ticking...and since key up will always set it to some value, it will never be false.
Also, you add add and reset timer for each input. If you want the user to spend at least 5 seconds to fill in your form, dont enable the submit button until 5 sec has passed.
function doneTyping () {
checktime = typingTimer;//will always have a value that evaluates to true
return checktime;
}
Try that... HTML:
<form id="registerform" class="registerform" method="post">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
jQuery:
jQuery(document).ready(function ($) {
var intervalTime = 5000,
inputID = "#submit";
function initialize(interval, input) {
intervalTime = interval;
inputID = input;
jQuery(inputID).prop("disabled", true);
startCouting();
}
function startCouting() {
setTimeout(function() {
enableInput();
}, intervalTime);
}
function enableInput() {
jQuery(inputID).prop("disabled", false);
};
initialize(5000, "#submit");
});

Can't get javascript to redirect to another html page upon button click

I am trying tot get my javascript code to redirect to the Index.html page if the variable money is equal to 100. Here is the html form code:
<form id = "form" action = "">
<h1> Enter the amount of money you would like to spend on your next trip. </h1><br>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" name="money" class="form-control">
</div>
<br>
<button type="submit" class="btn btn-default" onclick = "MoneyForTrip()">Show Trips</button>
</form>
and the javascript:
var money;
function MoneyForTrip()
{
money = parseInt(
document.getElementById('form').money.value);
if (money == 100)
{
window.location="Index.html";
}
else
{
window.alert("Enter another number");
}
}
Any idea how I can get it to redirect to Index.html if money is equal to 100?
Try this.
window.location.replace("Index.html")
or
window.location.href = "Index.html"
Also take a look at this Stack Answer.
Use the submit event instead of button's click event:
var money;
var form = document.getElementById('form');
form.onsubmit = function(e) {
e.preventDefault();
money = parseInt(document.getElementById('form').money.value);
if (money == 100){
window.location="Index.html";
}
else{
window.alert("Enter another number");
}
}
Demo: http://jsfiddle.net/xzjW3/
try
<input type="text" name="money" id="moneyfortrip" class="form-control">
var money;
function MoneyForTrip()
{
money = parseInt(
document.getElementById('moneyfortrip').value);
if (money == 100)
{
window.location="Index.html";
}
else
{
window.alert("Enter another number");
}
}

Categories

Resources