Automatic click Submit after 10 seconds in php using jquery - javascript

I am trying to auto submit for after 10s in PHP using jquery. but no action is done.
I tried:
<?php echo "<div class="page-header">
<h1 class="h2"></h1>
</div>
<script>
var checkState = function(){
jQuery.ajax({
url: 'check_diffex.php?od=$scdate'
}).done(function(data){
if(data.diffex >= 10) {
$('#quizsb').submit();
});
}
checkState();
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jque‌​ry.min.js"></script>
<form method="post" action="qform.php?srn=<?php echo $srn ?>&id=<?php echo $id ?>" enctype="multipart/form-data" class="form-horizontal" id="quizsb">
.....
</form
"?>
check_diffex.php
<?php
header('Content-Type: application/json');
if(isset($_GET['od'])){
$deotd = $_GET['od'];
}
date_default_timezone_set('Asia/Calcutta');
$cdate = date('Y-m-d H:i:s ', time());
$scdate = strtotime($cdate);
$e = $scdate - $deotd;
// You would calculate a real value here
echo json_encode([
'diffex' => $e
]);
?>
Before Answering Please look at this comment

use setTimeout function.
Below code submit form automatically after 10sec from page load
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
setTimeout(function(){ document.getElementById("myForm").submit(); }, 10000);
</script>
</body>
</html>

Use Cookie instead if you don't want user to increase timeout, so set Cookie with 10 seconds lifetime and delete the cookie after that. Please apply your logic to delete the cookie after 10 seconds and always check if the cookie is set or not, if it is not, then submit the form.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

Related

Create text-input on button click in form

I want to create another input field, everytime the button "+" inside the form is clicked. I searched for a solution but i can't find anything. The input field should be created inside the form over the "+" button.
Here is my current code:
<div class="row">
<div class="col-md-12">
<form method="post" id="create-form" action="create.php" enctype="multipart/form-data">
<?php
/* getting sample questions */
/* checks result and creates variables from result */
if ($sampleamount > 0) { // amount
$samplequery->bind_result($questionid_sample, $question_sample);
while ($samplequery->fetch()) { // while page can use this variables
/* echo text-box, value from db */
$required = $questionid_sample === 1 ? "required" : ""; // one question is always required
echo "<input class='question-box' type='text' name='" . $questionid_sample . "' placeholder='Write your question in here.' maxlength='255' size='70' value='" . $question_sample . "'" . $required . "> <br>";
}
} else {
/* no result (db=sample_question) */
header('Location: ../index.php');
}
$samplequery->close();
closeDB($conn);
/* adds more input for user */
for ($i = ($sampleamount + 1); $i <= ($additionalquestions + $sampleamount); $i++) {
echo "<input class='question-box' type='text' name='" . $i . "' placeholder='Write your question in here.' maxlength='255' size='70'> <br>";
}
?>
<br>
<input class="createsurvey2" type="button" id="addqbtn" name="addqbtn" value="+" >
<br>
<input class="createsurvey2" type="submit" name="btnSubmit" value="Create Survey!" >
</form>
</div>
</div>
</div>
<script>
function addquestion() {
var counter = 2;
var addqbtn = document.getElementById('addqbtn');
var form = document.getElementById('create-form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'additionalquestion-' + counter;
input.type = 'text';
input.class = 'question-box';
input.name = 'name';
input.placeholder = 'Write your question in here.';
form.appendChild(input);
};
addqbtn.addEventListener('click', function(){
addInput();
}.bind(this));
};
</script>
<html>
<body>
<button onclick="createNewFiled()" id="incrementBtn" type="button">Click here</button>
<form id="form" action="">
</form>
</body>
</html>
<script type="text/javascript">
var counter = 0;
var incrementBtn = document.getElementById('incrementBtn');
var form = document.getElementById('form');
var createNewFiled = function() {
counter++;
var input = document.createElement("input");
var br = document.createElement("br"); // If you need new line after each input field
input.id = 'input-' + counter;
input.classList.add("inputClass");
input.type = 'text';
input.name = 'name'+counter;
input.placeholder = 'Input field ' + counter;
form.appendChild(input);
form.appendChild(br); // If you need new line after each input field
};
</script>

Trying to display login attempts and user lockout message after failed attempts

I am working on a login page for an FTP site. It runs off a Tomcat 8 server and is configured to lockout users after 3 failed attempts for 15 minutes. I would like to display a message on the login page after the user has been locked out. The problem is when there is a failed login the page refreshes (redirects back to login page) which clears everything.
I did managed to get a login attempts remaining error message, however, it doesn't work 100% because i just save it to a cookie and its not connected to the user account at all. Is there anyway to get username (who's logging in) and their login attempts and/or if they are locked out?
So I want to display 2 things:
Login attempts remaining per user
User is locked out, with username
Login page:
<%#page import="org.apache.catalina.User"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/master.css">
<script type="text/javascript" src="<%=request.getContextPath()%>/javascript/javascript.js"></script>
</head>
<body bgcolor="#ffffff">
<div class="container" role="main">
<form method="POST" action="j_security_check">
<table border="0" align="center">
<tr>
<td>Login</td>
<td><input id="user" type="text" name="j_username" autocomplete="off"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="j_password" autocomplete="off"></td>
</tr>
</table>
<%
User user = (User) request.getSession().getAttribute("user");
System.out.println("User: " + user);
if (request.getParameter("error") != null) {
System.out.println("Error: " + request.getParameter("error"));
%>
<div id="errorLogin">Invalid username or password</div>
<br/>
<div><span id="loginAttempt"><script>loginAttempts("<%=user%>");</script></span></div>
<%
}
%>
<input type="submit" value="Login">
</form>
</div>
<% response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache"); // HTTP 1.0
response.setHeader("Expires", "0"); // Prevents cache at proxy server
%>
</body>
</html>
javascipt.js
var loginattempts = null;
var temp;
function loginAttempts(user) {
//var user = document.getElementById('user').value;
var div = document.getElementById('loginAttempt');
var msg = "Warning: Login attempts remaining: ";
loginattempts = getCookie("login");
if (loginattempts === "" || loginattempts === null) {
createCookie("login", 3, 5);
temp = getCookie("login");
div.textContent = msg + temp.toString();
} else if (loginattempts === "0" || loginattempts === 0) {
div.textContent = user + " has been locked out";
} else {
temp = getCookie("login") - 1 ;
div.textContent = msg + temp.toString();
}
debugger;
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function createCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
server.xml lockout:
<Realm className="org.apache.catalina.realm.LockOutRealm" failureCount="3" lockOutTime="900" cacheSize="1000" cacheRemovalWarningTime="3600">
I've solved this myself, I am using cookies to store the information.

Remember last selected option from dropdown

I want that our website should remember the last selected option from drop down when he visit again. I'm trying it with jQuery cookies but it's not working.
Here is my select dropdown code
<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val"><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
Beacuse i'm using it as filter with my search bar i read the value on keyup function my jquery i tried is
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = Cookies.get('dropdown');
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
As you can see I tried to use cookie to remember the selection but its not working as it takes the first option again when the page is refreshed.
You can use Jquery.Cookie for this case.
https://github.com/carhartl/jquery-cookie
Then save dropdown value in cookie like :
jQuery(document).ready(function(){
var selectedVal = jQuery.cookie("selected-val");
if (selectedVal) {
jQuery("#city").val(selectedVal);
}
jQuery("#city").on("change", function(){
var selection = jQuery(this).val();
jQuery.cookie("selected-val", selection, {expires: 365, path: '/'})
});
});
I assume you are using js-cookie or similar?
This is not tested, but if the cookie is set then you could do the following:
<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val" <?php echo (!empty($_COOKIE['dropdown']) && $_COOKIE['dropdown'] == $rows['c_id'] ? 'selected' : ''); ?>><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
Notice where php checks $_COOKIE['dropdown'] and outputs selected if it equals the option value on this line:
<option value= "<?php echo $rows['c_id']?>" id="optin_val" <?php echo (!empty($_COOKIE['dropdown']) && $_COOKIE['dropdown'] == $rows['c_id'] ? 'selected' : ''); ?>><?php echo $rows['city_nm'];?></option>
Please refer this answer you might get some help..
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "dropdown=" + val + expires + "; path=/";
// Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = getCookie("dropdown");
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
if (c.indexOf(name) == 0) {
return (c.substring(name.length, c.length));
}
}
}

Submit method not being called when timer reaches zero in php using javascript

Im creating a sample quiz webpage using codeigniter. And in my one of the views there is a scenario where there is a timer and when it reaches zero the form should be submitted. I have tried a code and the timer works but when it reaches zero the call to submit is not being done, so im unable to navigate to the next page. But when submit button is clicked with works fine. Below is my code. Can anyone help me find where im going wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Your Knowledge</title>
<script type="text/javascript">
var totalsec = 50;
var c_min = parseInt(totalsec / 60);
var c_sec = parseInt(totalsec % 60);
function CheckTime() {
document.getElementById("timer").innerHTML = "Time left: " + c_min + " min " + c_sec + " sec ";
if (totalsec <= 0) {
document.getElementById("difficultyForm").submit();
} else {
totalsec = totalsec - 1;
c_min = parseInt(totalsec / 60);
c_sec = parseInt(totalsec % 60);
setTimeout("CheckTime()", 1000);
}
}
setTimeout("CheckTime()", 1000);
</script>
<style type="text/css">
</style>
</head>
<body>
<div id="container">
<h1>Welcome to Test Your Knowledge!!!</h1>
<div id="body">
<h2>Selected the difficulty level: Easy</h2>
<div><span id="timer"></span></div>
<form action="/AWT_CW1/index.php/ResultController/" method="POST" id="difficultyForm" name="difficultyForm">
<?php
foreach ($quesAnsList as $quesAns) {
echo '<question>';
echo '<strong>' . $quesAns->question . '</strong>';
echo '<br>';
echo '<input type="radio" name="' . $quesAns->answer_id . '" value="' . $quesAns->answer1 . '">' . $quesAns->answer1 . ' <br>';
echo '<input type="radio" name="' . $quesAns->answer_id . '" value="' . $quesAns->answer2 . '">' . $quesAns->answer2 . ' <br>';
echo '<input type="radio" name="' . $quesAns->answer_id . '" value="' . $quesAns->answer3 . '">' . $quesAns->answer3 . ' <br>';
echo '</question>';
}
?>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
Note: I was asked not to use jquery or ajax for this project. Thanks in advance.
Why your code is not working
That's because you named your submit button "submit", overriding the submit() function.
How you can fix the problem
You can fix it by replacing
<input type="submit" name="submit" value="Submit">
With
<input type="submit" name="submit_button" value="Submit">
Please keep in mind that...
As #Rajesh pointed out in the comments, setTimeout expects a function as first argument, while you're providing a string.
Replace setTimeout("CheckTime()", 1000); with
setTimeout(function(){
CheckTime();
}, 1000);
setTimeout
Calls a function or executes a code snippet after a specified delay.
Syntax: setTimeout(function(), delay);
setInterval
Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.
Syntax: setInterval(function(),interval)
setInterval Implementation of your code
JSFiddle.
For simulation purpose, I have reduced timer to 10sec.
(function () {
var totalsec = 10;
var interval = null;
function CheckTime() {
document.getElementById("timer").innerHTML = "Time left: " + parseInt(totalsec / 60) + " min " + (totalsec % 60) + " sec ";
if (totalsec <= 0) {
window.clearInterval(interval)
document.getElementById("difficultyForm").submit();
} else {
totalsec--;
}
}
function initInterval() {
interval = setInterval(function () {
CheckTime()
}, 1000);
}
initInterval();
})()
<span id="timer"></span>
<form id="difficultyForm">
</form>

How to handle javascript made inputs

I have a problem, i searched for the solution all over the internet, but i couldn't find it out :S
The problem is:
I'm creating file inputs on button click, but i can't handle these javascript made inputs because they aren't in my $_FILES array after i click on submit..
My code is:
HTML:
<form name = "galleryupload_form" method = "post" action = "#" enctype="multipart/form-data">
<ul id = "formul">
</ul>
<input type="button" value="Még egy kép feltöltése" onClick="addInput('formul');">
<input name = "galleryupload_submit" type = "submit" value = "Küldés"/>
</form>
javascript:
var counter = 0;
var limit = 5;
function addInput(ulName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newli = document.createElement('div');
newli.innerHTML = "<label for = ''>Fájl " + (counter + 1) + "</label><input type='file' name='files[]'>";
document.getElementById(ulName).appendChild(newli);
counter++;
}
}
If you now the solution, please let me know. Thank you.
Referring to the question before editing:
File inputs appear in $_FILES not $_POST.
After editing, I cannot reproduce the problem.
check this code .
<?php
if(isset($_POST['galleryupload_submit'])){
print_r($_FILES);
}
?>
<form name = "galleryupload_form" method = "post" action = "" enctype="multipart/form-data">
<ul id = "formul">
</ul>
<input type="button" value="My textbox goes" onClick="addInput('formul');">
<input name ="galleryupload_submit" type ="submit" value ="Click Add"/>
</form>
<script>
var counter = 0;
var limit = 5;
function addInput(ulName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}else {
var newli = document.createElement('div');
newli.innerHTML = "<label for = ''>New TexBOx " + (counter + 1) +"</label><input type='file' name='files[]'>";
document.getElementById(ulName).appendChild(newli);
counter++;
}
}
</script>

Categories