Keep user logged in between browser sessions - javascript

Here is the sample code for my project. It contains two forms on a single page.
The first form contains username and a textbox, when I enter the username and click the login button the user's name should be displayed and the logout form should be displayed.
How do I ensure that the user will remain logged in once the browser window is closed?
Code
<!DOCTYPE html>
<html>
<title>Login Page</title>
<head>
<script>
function set(x)
{
document.getElementById(x).value="";
}
</script>
<script>
function showDiv(e)
{
var divs = document.getElementsByTagName('div');
if (e==1)
{
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="visible";
else if (divs[i].id=="hidevar2")divs[i].style.visibility="hidden";
}
}
else {
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="hidden";
else if (divs[i].id=="hidevar2") {
divs[i].style.visibility="visible";
}
}
}
}
function put()
{
var x = document.getElementById("fname").value;
currentTime=new Date();
if(currentTime.getHours()<12)
var y = "Good Morning ";
else if(currentTime.getHours()<17)
var y = "Good Afternoon ";
else
var y = "Good Evening ";
document.getElementById("devin").innerHTML = "Hello " + x + " " + y;
}
</script>
<script>
</script>
<script>
function search()
{
var dic = document.getElementById("url").value;
var str="http://www.google.co.in/#hl=en&q=";
var www=str+dic;
window.open(www);
}
</script>
</head>
<body>
<div id="devin">
</div>
<div id="hidevar1" style="visibility: visible;">
<form name="frm1" method="post" >//Login form
User Name : <input type="text" id="fname" value="Enter name here" onfocus="set(this.id)" >
</form>
<input type="button" value="Login" onClick="showDiv(2);put();">
</div>
<div id="hidevar2" style="visibility: hidden;">
<form name="frm2">//logout form
<script>
</script><br/>
<input type="submit" value="logout">
<br>
<br>
</form>
</div>
<br><br>
<input type="text" name="url1" id="url" />
<input type="submit" value="google"onclick="search();" />
</body>
</html>

If you plan to use spring, spring-security provides remember me services which would let you be logged in across browsers or sessions.
Other option is to use Apache shiro if you find spring-security too complex for your application.

Related

Trying to get cookies to prepopulate fields in a form in html

Hi I am new to software development and working on code. I am trying to get cookies to populate a field in my form when a user has input into it previously. However not able to work it out.
I have tried to setcookies and getcookies to work , however just cannot populate the form value for some reason. I am getting undefined in the field.
<script>
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value) {
document.cookie = name + "=" + escape(value) + "; path=/; expires=" +
expiry.toGMTString();
}
</script>
<script>
function storeValues(form) {
setCookie("phoneNumber", form.phoneNumber.value);
return true;
}
</script>
<script type="text/javascript">
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
<body>
<form name="contactInfo" id="contactInfo" autocomplete="on" action="/javascript/getcookie/" onsubmit="storeValues(this)">
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" onfocus="this.placeholder=''" onblur="this.placeholder='e.g. 0412345678' ; validatePhoneNumber(this)" required>
<input type="submit" class="submit" id="post-btn" value="Call Me" />
</form>
<script>
document.getElementById("phoneNumber").value = document.write(getCookie("phoneNumber"));
</script>
</body>
I am expecting to get the number that i previously entered into the form to populate the next time I load the page.
Try to use the sessionStorage instead of cookiee .
It saves a lot of coding hack.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onLoad="getSession()">
<form >
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" required>
<!-- <button onClick="validatePhoneNumber(this)">Submit</button> -->
<input type="submit" class="submit" id="post-btn" value="Call Me" onClick="validatePhoneNumber(this)"/>
</form>
</body>
</html>
<script>
function validatePhoneNumber(){
var value = document.getElementById("phoneNumber").value;
console.log(value)
sessionStorage.setItem("phoneNumber", value);
}
function getSession(){
console.log("hey");
var session = sessionStorage.getItem("phoneNumber");
document.getElementById("phoneNumber").setAttribute("value" , session);
}
</script>
Notice :- Removed some attribute and field because i am not having that data , you can add according to your necessity .
For more detail about sessionStorage , visit LINK

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

there are two html pages. I want the data status of first pages to saved when I reverting from next page to first page

When I click on back button of next page the check box value should not be reset.
It should be same as I checked or unchecked. The code from the first and next page is below.
First Page
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" name="code" value="ECE">ECE<br>
<input type="checkbox" name="code" value="CSE">CSE<br>
<input type="checkbox" name="code" value="ISE">ISE<br>
<br>
<input type="button" onclick="dropFunction()" value="save">
<br><br>
<script>
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
</script>
</form>
</body>
</html>
Next Page
<html>
<head>
<title>Welcome to </title>
</head>
<body color="yellow" text="blue">
<h1>welcome to page</h1>
<h2>here we go </h2>
<p> hello everybody<br></p>
</body>
<image src="D:\images.jpg" width="300" height="200"><br>
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.location.href="first.html";
}
</script>
</body>
</html>
Full solution: example. First add ids to your checkboxes:
<input type="checkbox" name="code" value="ECE" id='1'>ECE<br>
<input type="checkbox" name="code" value="CSE" id='2'>CSE<br>
<input type="checkbox" name="code" value="ISE" id='3'>ISE<br>
<input id="spy" style="visibility:hidden"/>
Then change your dropFunction:
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
localStorage.clear();
for (var i = 0; i < branch.length; i++)
if (branch[i].checked == true)
localStorage.setItem(branch[i].id, true);
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
And add some new javascript code to first.html:
window.onload = function() {
var spy = document.getElementById("spy");
if(spy.value=='visited')
for(var i=1;i<=3;i++)
if(localStorage.getItem(i))
document.getElementById(i).checked=true;
spy.value = 'visited';
}

Why our page is loaded when I click on button

In below code actually I got form design in popup using onload(). In function login() first I check every field is required then in else part I call loginvalidate.php page without page refresh in this page I perform validation in php and if any error show it in
<div id="result" style="color:red;"></div>
Division, But my query is that after if part is completed in login function and when I click on button in else part our page is reloaded because of this reload I can't access my loginvalidate.php page why this is happen please suggest me,
<!doctype html>
<html>
<head>
<script src="jquery-1.11.3.js"></script>
<meta charset="utf-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script>
function login(){
var email=document.getElementById("email").value;
var password=document.getElementById("pass").value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if(email=="" || password==""){
alert("Every Field Is Requird");
email.password.focus();
return false;
}else{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data){
$('#result').html(data);
});
return false;
}
}
function popup(){
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
</script>
</head>
<body onload="popup();">
<div id="light" class="white_content" style="height:53%">
<img class="close" src="/shopeeon/custom-look/newloginpopup/close.jpg" class="close" href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';history.go(-1);"></img>
<!--go back to previous page using "history.go(-1)" onclick-->
<div id="abc">
<div id="popupContact-login" class="col-sm-12" >
<form action="" id="login-form" method="post" name="form">
<div style="color:orange;text-align:center;width:100%;">
<h2 style="margin:0px;">Login to Earn Extra Cashback</h2>
<div id="result" style="color:red;"></div>
</div><br/>
<div class="col-sm-6 align="center" style="border-right:1px solid gray;" > <?php $reg1 = <<<var<b style="font-size:20px;font-family:arial;"> Registered User,</b> var; $reg2=<<<var<b style="color:blue;font-size:20 px;font-family:arial;"> Sign In Here </b> var; echo $reg1.$reg2; ?> </br> <input type="email" id="email" class="form-control" name="uemail" placeholder="Enter email" required/><br/>
<input type="password" id="pass" class="form-control" name="upass" placeholder="Enter password" required/><br/>
<button type="submit" onclick="return login()" id="submit" name="submit" value="submit" class="btn btn-info active btn-md">SIGN IN</button><br/>
Else Redirect without Sign In
</div>
<div class="col-sm-6" > <?php $str1 = <<<var <b style="font-size:20px;font-family:arial;"> New User,</b> var; $str2=<<<var <b style="color:blue;font-size:20 px;font-family:arial;"> Sign Up Here </b> var; echo $str1.$str2;?>
<img src="/shopeeon/custom-look/newloginpopup/link.png" height="38"></img><br/> <?php $s1 = <<<var <b style="font-size:12px;font-family:arial;"><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> WE OFFER CASHBACK WHEN YOU SHOP VIA US.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> OVER 2 LAKH CASHBACK PAID.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> OVER 1 LAKH HAPPY CUSTOMERS.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> 25+ PARTNERS SITES.</br>var; echo $s1;?>
</div >
</form>
</div>
</div>
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html>
While click the button form submit will trigger, it's reload the page. So give onsubmit="return false" to form for prevent the page load.
Like below code
<form onsubmit="return false">
</form>
Hope this will help you.
1st: what that line expect to do?? email.password.focus(); it will give you an error .. so you can use
if(email=="" || password=="")
{
alert("Every Field Is Requird");
if(email == ""){
email.focus();
}
// check the same way for password
}
else......
2nd: better to don't mix jquery with pure javascript
3rd in your function it submit a form before prevent the page from reloading so you can use
in html
<form onsubmit="login();"> // instead of the submit input click event
and your function
function login()
{
var email=$('#email').val();
var password=$("#pass").val();
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if(email=="" || password=="")
{
alert("Every Field Is Requird");
//email.password.focus();
}
else
{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data)
{
$('#result').html(data);
});
}
return false;
}
or you can use e.preventDefault();
<form onsubmit="login(e);"> // instead of the submit input click event
and your function
function login(e)
{
e.preventDefault();
var email=$('#email').val();
var password=$("#pass").val();
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if(email=="" || password=="")
{
alert("Every Field Is Requird");
//email.password.focus();
}
else
{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data)
{
$('#result').html(data);
});
}
//return false;
}

Replace innerhtml on form submit with javascript

I want to have a form that asks the user their name, then welcomes them to the website with that name without redirecting to a different page or reloading. So basically replace a form with "Welcome NAME" after submit is clicked.
My code:
<div id="welcomeText">
<form onsubmit="changeText()" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById(welcomeForm).fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
You need to give a name to the form before trying to access it, something like this:
//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<script>
function changeText() {
//access myForm using document object
var name = document.name.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<div id="welcomeText">
<form onsubmit="changeText()" method="post" id="welcomeForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById("welcomeForm").fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="welcomeText">
Name: <input type="text" name="fname" id="name">
<input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">
</div>
<script>
function changeText() {
var name = document.getElementById("name").value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
document.getElementById("name").style.display = "none";
document.getElementById("submit").style.display = "none";
}
</script>
</body>
</html>
Try this it will display "welcome user" and also make button and input disappear. In this case you don't even need a form. You can access the name directly from the input without ever submitting the form.
Here we are:
<div id="welcomeText">
<form id="myform" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
var form = document.getElementById("myform");
form.addEventListener('submit', function (e) {
e.preventDefault(); // This will prevent submitting the form
var name = form.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
});
</script>

Categories