Below is a logon code I have set up with html. I would like to set a timeout setting to initiate a log off function after x minutes idle time. Is this possible? I currently have a log off button that initiates the log off, so possibly have that timeout select that function. Thank you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>Enter credentials</legend>
<p>
<label for="username">User name:</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</p>
</fieldset>
<input type="submit" id="login-button" name="login-button" value="Log On" />
</form>
<script src="scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Web Proxy request to fetch the configuration
ajaxWrapper({ url: 'Home/Configuration', dataType: 'xml', success: configSuccess });
$('form').submit(function () {
var username = $('#username').val(),
password = $('#password').val();
clearMessage();
if (!username || !password) {
showMessage('Enter a username and a password');
return false;
}
// Ensure the user name is correct...
// If the username has the domain string at position 0, then
// the username is correct and just use it as normal, but if
// not, username needs to have the domain prepended.
// Because of the backslashes in the strings, they need to be
// escaped with "\\"
username = username.indexOf("domain\\") === 0 ? username : "domain\\" + username;
// Web Proxy request to log the user on
ajaxWrapper({
url: 'PostCredentialsAuth/Login',
dataType: 'xml',
success: loginSuccess,
error: loginError,
data: { username: username, password: password }
});
return false;
});
});
</script>
Below is the code I added to the section after the logonsuccess form is selected.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Set timeout variables.
var timoutWarning = 60000; // Display warning in 14 Mins.
var timoutNow = 30000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = '($configXml.find('authManager').attr('logoffURL'));'; // URL to logout page.
var warningTimer;
var timeoutTimer;
// Start warning timer.
function StartWarningTimer() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
}
// Reset timers.
function ResetTimeOutTimer() {
clearTimeout(timeoutTimer);
StartWarningTimer();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
clearTimeout(warningTimer);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
$("#timeout").dialog({
modal: true
});
// Add code in the #timeout element to call ResetTimeOutTimer() if
// the "Stay Logged In" button is clicked
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
And below is the Log Off button that is shown where a user can manually log off.
$('#log-off').click(function () {
// Web Proxy request to log the user off
url = ($configXml.find('authManager').attr('logoffURL'));
ajaxWrapper({ url: url, dataType: 'text', success: logoffSuccess });
return false;
});
});
Your code doesn't call incativityTime function. Call the function on window onload (or jquery onready) like window.onload = function() { inactivityTime() };
<html>
<body>
<script>
window.onload = function() { inactivityTime() };
var inactivityTime = function ()
{
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
}
</script>
</body>
</html>
I added it with no success. Below is how the logon success code looks.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Web Proxy request to enumerate the resources available to the user
url = $configXml.find('resourcesProxy').attr('listURL');
ajaxWrapper({ url: url, success: listResourcesSuccess });
} else {
showMessage('Login failed - try again');
}
var inactivityTime = function () {
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
};
}
Related
I am not a Javascript wiz so need some help with the following. I have a popup asking people to type in their email address. Right now the popup just closes after submission, which isn't a nice user experience. Ideally the text bar and the submission button would disappear, and be replaced by a short comment such as "Thanks, we'll be in touch". Even better would be if the popup would then disappear after "N" seconds.
Can anyone help?
var self = this;
var showDelay = parseInt('[[ bannerShowDelayInMilliseconds ]]' || '0', 10);
setTimeout(function () {
requestAnimationFrame(function () {
if (!self.inPreview && "true" == "{{ 'true' if customer.email else 'false' }}") {
return;
}
self.sdk.track('banner', getEventProperties('show', false));
document.body.insertAdjacentHTML('beforeend', self.html);
var banner = self.banner = document.querySelector('.exponea-subscription-dialog');
self.backdrop = document.querySelector('.exponea-subscription-dialog + .exponea-banner-backdrop');
banner.insertAdjacentHTML('afterbegin', '<style>' + self.style + '</style>');
var form = banner.querySelector('form');
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("dialogue").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
};
var btnClose = banner.querySelector('.exponea-close');
btnClose.onclick = function () {
removeBanner();
self.sdk.track('banner', getEventProperties('close'));
};
});
}, showDelay);
function getEventProperties(action, interactive) {
return {
action: action,
banner_id: self.data.banner_id,
banner_name: self.data.banner_name,
banner_type: self.data.banner_type,
variant_id: self.data.variant_id,
variant_name: self.data.variant_name,
interaction: interactive !== false ? true : false,
location: window.location.href,
path: window.location.pathname
};
}
function removeBanner() {
if (self.banner) {
self.banner.parentNode.removeChild(self.banner);
}
if (self.backdrop) {
self.backdrop.parentNode.removeChild(self.backdrop);
}
}
function validateEmail(email) {
return email && /^\S+#\S+\.\S+$/.test(email);
}
return {
remove: removeBanner
};
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("thankYouIdExample").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
Just make sure to place the <div id="thankYouIdExample"></div> at the right place.
Let me know if it works for you m8
You can insert your thanks message in another container, and write something like this:
<div id="container">
<div id="form">
here is the form and everything that belongs here
</div>
<div id="thanks">
here is the thanks message
</div>
</div>
With this, you can set the default style of the thanks div to display: none; in css.
If you reference the container divs in js by their ids, you can change their style from js. The setTimeout() method can be used to time the closing of the dialog box, assuming it is done by the removeBanner() function. You can add these lines:
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("form").style.display = 'none';
document.getElementById("thanks").style.display = 'block';
setTimeout(function(){removeBanner();}, 5000);
}
return false;
This way you can have a fully pre-customized thanks message.
Use setTimeout
https://www.w3schools.com/jsref/met_win_settimeout.asp
https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setTimeout
form.onsubmit = function() {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
return false
}
Asynchronous version (if you want to return after the 5000 wait):
*only useful if you not directly call the handler
form.onsubmit = async function() {
return Promise((resolve, reject) => {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
resolve()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
else reject()
})
}
users can sign in to my system using google sign in so when use pressing google sign in button his account will be create in mysql database
my problem is every users account created two time when user trying to sign in by google
in other words function of create account executed two time for every user
here is my html code
<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>
this is javascript code
function gPOnLoad(){
// G+ api loaded
document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
gapi.auth.signIn({
callback: 'gPSignInCallback',
clientid: '636950137786-j3siaftgshtf9iamovisf603pplv7jf1.apps.googleusercontent.com',
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/user.birthday.read"
})
}
function gPSignInCallback(e) {
if (e["status"]["signed_in"]) {
gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
getProfile()
} else if (e["error"]) {alert(e['error'])
console.log("There was an error: " + e["error"])
}
})
} else {alert(e["error"]);
console.log("Sign-in state: " + e["error"])
}
}
function getProfile() {
//var e = googleData.getBasicProfile();
var e = gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {alert(e.message)
console.log(e.message);
return
} else if (e.id) {var msgs=JSON.stringify(e);
alert(e.displayName);
update_user_data(e);
// save profile data
}
})
}(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})()
function update_user_data(response)
{
// var dataString = JSON.stringify(response);
var email=response.emails[0]['value'];
var displayName=response.displayName;
//ar
$.ajax({
type: "POST",
data: {email:email,displayName:displayName},
url: 'Save.php?id=check_user',
success: function(msg) {
var array = msg.split(',');
var email =array[0];alert(email);
var password = array[1];alert(password);
$('#username').val(email);$('#password').val(password);
document.getElementById("modal4c").click();
},
error: function(XMLHttpRequest,textStatus,errorThrown) {//alert(JSON.stringify(msg));
}
});
}
update_user_data() function is to insert account into mysql database but this function is called twice per user.
Not sure why you function runs twice but,
one way to ensure a function runs only once would be make some global flag like this
runOnce = false;
function gPSignInCallback(e) {
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
If you want to avoid global vars you could return a closure like this
function update_user_data(e){
var runOnce = false
return function(){
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
}
And call it like this update_user_data()(e)
I'm trying to automatically run the onclick function in one button placed in phtml template.
This is the html file with the button code:
<button type="button" id="review-btn" title="<?php echo $this->__('Place Order') ?>" class="button btn-checkout" onclick="review.save();"><span><span><?php echo $this->__('Place Orderxxxxx') ?></span></span></button>
This is part of javascript file with save and review functions:
//review function starts
var Review = Class.create();
Review.prototype = {
initialize: function(form,saveUrl,successUrl,agreementsForm){
this.form = form;
this.saveUrl = saveUrl;
this.successUrl = successUrl;
this.agreementsForm = agreementsForm;
this.onSave = this.nextStep.bindAsEventListener(this);
this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
},
//function triggers when onloading on review save function
loadingbox: function () {
var translate = Translator.translate('processing').stripTags();
$("review-please").update(' <div class="please-wait-loading"> </div><span class="load-wait">'+translate+'</span>')
var form = $('review-btn');
form.disabled='true';
},
save: function(){
var paymentmethod = payment.currentMethod;
var validator = new Validation(this.form);
if (validator.validate()) {
var request = new Ajax.Request(
this.saveUrl,
{
method:'post',
parameters: Form.serialize(this.form),
onLoading:this.loadingbox.bind(this),
onComplete: this.onComplete,
onSuccess: function(transport) {
if(transport.status == 200) {
var data = transport.responseText.evalJSON();
if(!data.success)
{
alert(data.error_messages);
$("review-please").update('');
$('review-btn').disabled='';
}
if (data.redirect) {
location.href = data.redirect;
return;
}
if(data.success){
//hostedpro and advanced payment action
if(paymentmethod == 'hosted_pro' || paymentmethod =='payflow_advanced')
{
Element.hide('review-please');
Element.hide('review-btn');
document.getElementById('checkout-paypaliframe-load').style.display= 'block';
iframedata = data.update_section["html"].replace("display:none","display:block");
document.getElementById('checkout-paypaliframe-load').innerHTML = iframedata;
}
else //other payment action
{
this.isSuccess = true;
window.location = data.success;
}
}
}
},
onFailure: checkout.ajaxFailure.bind(checkout)
}
);
//var updater = new Ajax.Updater('product-details', this.saveUrl, {method: 'post',parameters: Form.serialize(this.form)});
}
},
If I simply change the onclick to setTimeout it doesn't work.
Use setTimeout in your javascript file.
Second parameter is time in milliseconds (1000ms = 1s), after which function will be executed.
setTimeout(review.save, 1000);
EDIT:
Sinde you use this in your function, you need to overwrite this. If called independently, scope isn't same anymore.
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
Full code
Add this to last row of your JS file.
window.onload = function(){
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
};
I am trying to do login with the help of Jquery ajax, but at the time of making ajax call using method jQuery.ajax(....) with servlet (Java) this method was unable to call. I am using ajax lib from link http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js.
Every time I am getting the below URL in address bar of browser.
Project/?email=abc88%40gmail.com&password=1234&sendbtn=Send+Message
Below is the Jquery Ajax Code.
$(document).ready(function() {
//global vars
var username=jQuery("#email");
var password=jQuery("#password");
function checkLoginForm() {
if(username.attr("value") && password.attr("value")) {
return true;
} else {
return false;
}
}
jQuery(".txtbar, .txtbox").live("focus", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
var pxlchange = '-45px';
rowbox.addClass('colors');
thelabel.animate({left: pxlchange}, 350, 'linear', function() {});
// The animation is completed
infobox.animate({opacity: 1.0}, 350, 'linear', function() {
// The animation is completed
});
}
jQuery(this).live("keyup", function() {
var theval = jQuery(this).val();
var limitval = 3;
var replacehtml = "";
var emailinfohtml = "Enter a valid e-mail address.";
var subjectinfohtml = "Enter Password.";
if(currid == "email") {
replacehtml = emailinfohtml;
} else if(currid == "password") {
replacehtml = subjectinfohtml;
limitval = 2;
}
// checking against e-mail regex
if(currid == "email") {
if(checkValidEmailAddress(theval)) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(!checkValidEmailAddress(theval)) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
} else {
// we use this logic to check for name+message fields
if(theval.length >= limitval) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(theval.length < limitval) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
}
// now we check if we can display the send button
// much easier to just look for 'good class on the req fields
});
});
jQuery(".txtbar, .txtbox").live("blur", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
rowbox.removeClass('colors');
infobox.animate({opacity: 0}, 400, 'linear', function() {
// The animation is completed
});
});
jQuery("#sendbtn").click(function() {
if (checkLoginForm()) {
jQuery.ajax({
type : "GET",
url : "/DoLogin.htm",data:"userName="+ username.val()+ "&password="+ password.val(),
success : function(msg) {
alert("Ajax Return Success");
return false;
}
});
} else {
alert("Ajax Return Fail Code ");
return false;
}
});
function checkValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+") ([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
HTML code:
<div id="wrap">
<form id="contact-form" name="contact-form">
<div class="rowbox">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" class="txtbar req" tabindex="1">
<div class="infobox">
Enter a valid e-mail address
</div>
</div>
<div class="rowbox">
<label for="subject">Password</label>
<input type="password" id="password" name="password" class="txtbar" tabindex="1">
<div class="infobox">
Enter Password
</div>
</div>
<input type="submit" value="Send Message" id="sendbtn" name="sendbtn" class="submit-button">
</form>
</div>
If you make the data property an object, jQuery will handle parameterizing and URI-encoding it for you automatically. If you insist on it being a string, you need to do all of that yourself.
jQuery.ajax({
type: "GET",
url: "/DoLogin.htm",
data: { userName: username.val(), password: password.val() },
success: function() {
alert("Ajax Return Success");
}
});
On a security note, I wouldn't simply check that the #email and #password fields have value attributes and return true, nor would I transmit plain-text login info over the wire. Maybe you intended this as boilerplate code to get things working and you'll validate/encrypt them better later. :)
Am trying to create a login page for my windows 8 app, am using Html5 and javascript.. so have tried to use winjs.xhr to post what is in the textboxes as variables to a specific url which is a php script so this is my example of the url "http://example.com/api/username=username&password=password" am using winjs.xhr to post these variables to the url but am not getting any response even in the console.log
this is my code
<script>
function handlelogin(){
document.getElementById("box").onsubmit = function(){
if(document.getElementById("email_address").value ==""){
document.getElementById("errormessage").innerHTML= "Please Provide Your Email Address";
return false;
}else{
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if(success == 1703){
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
};
}
window.onload = function () {
handlelogin();
}
</script>
<form id="box" method="post" name="loginform">
<p>Email address</p>
<div class="email_address"><input type="text" id="email_address" /></div>
<p>Password</p>
<div class="password"><input type="password" id="password" /></div>
<p><span id="errormessage"></span></p>
<div class="button"><input type="submit" id="login" value="Sign In"/></div>
<p>ForgotPassword?</p>
</form>
First - don't use a submit button. Use a input type="button". No submit required, you are simply reading the values on the page.
Second - attach the event handler for the button's click event. Doing this 'onload' for the window isn't the right place.
Third - don't use 'onsubmit' for your 'box' element. There is no form submission going on here. There shouldn't usually be a form submit in WinJS - that's for a browser posting the page to the server. You already are POSTing your data. See the updated code:
I highly recommend putting ALL javascript into separate files, as you'll get bytecode optimization that way. Inline Javascript isn't optimized for the next load. A common way you could do this is include the onload code below (where I assign onclick) in your js file like so
app.onactivated = function (args) {
..
..
..
args.setPromise(WinJS.UI.processAll().then(function () {
document.getElementById("login").onclick = handlelogin;
}));
..
..
}
};
But the answer directly for your question above is:
<script>
function handlelogin() {
if (document.getElementById("email_address").value == "") {
document.getElementById("errormessage").innerHTML = "Please Provide Your Email Address";
return false;
} else {
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({
type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if (success == 1703) {
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
}
window.onload = function() {
document.getElementById("login").onclick = handlelogin;
};
</script>
Check out some of the sessions in App Builder where they discuss JavaScript projects http://aka.ms/stackbuilder