Trouble using session storeage to show message after form submission - javascript

I am trying to use session storage to show a message once a form has been submitted. I have it working to a point, but wanted to know if there is a better to optimise this code? Thanks in advance
Caling the function here;
$(document).on('click', '#submit', function() {
window.history.replaceState(null, null, "?account=pending");
$(this).addClass('active');
$('.reset__button').removeClass('active');
$('.create_account_b2b').hide();
$('.login_account_b2b').show();
$('.reset_password_b2b').hide();
handleMessage();
});
Here is the function that with session storage
function handleMessage(){
var create = sessionStorage.getItem('account');
if(create == '1'){
// display the under review message here
sessionStorage.setItem('account','0');
$('p.login-message').text('Your Account Is Currently Under Review and we will be in touch within 2 weeks');
} else {
// toggle back to orginal message
sessionStorage.setItem('account','1');
$('p.login-message').text('Please login to access our Wholesale store');
}
}
handleMessage();

You could combine the Jquery part togerther.
$('.create_account_b2b, .reset_password_b2b').hide();
And
function handleMessage(action = 'login'){
// Default Message
$('p.login-message').text('Please login to access our Wholesale store');
if(action == 'create') {
$('p.login-message').text('Your Account Is Currently Under Review and we will be in touch within 2 weeks');
}
}
Now that we have added a default parameter string as login, on your page refresh you would see the login message.
Call the handleMessage function in your form submission by passing the parameter as
handleMessage('create')

Related

PayPal as secondary payment option in Braintree

We're currently struggling with Braintree PayPal payment in combination with regular bank transfer via IBAN. Basically, we present two subscription options to the visitor: PayPal (via Braintree) and IBAN transaction.
The PayPal method works fine but when we don't select PayPal but IBAN bank transfer, we're getting the following console error:
We understand that this is the correct behaviour since the PayPal fields are not filled, but how is it possible to have PayPal as an optional payment method without throwing an error when the fields are not filled?
We're using the basic js implemetion via DropUI.
<div class="bt-drop-in-wrapper" id="showpaypalfields">
<div id="bt-dropin" class="paypaldiv"></div>
</div>
<script src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js"></script>
<script>
var client_token = "123TOKEN";
braintree.setup(client_token, "dropin", {
container: "bt-dropin"
});
</script>
UPDATE:
Both forms are visible on the page instantly, they are not loaded afterwards via Ajax or any kind. So, the PayPal option via Braintree should only validate if for example a checkbox is set. For example, the checkbox given in the screenshot below (toggles visibility of both fieldsets).
UPDATE #2:
For anyone interested in the final solution:
var btInstance;
$('input#paymentmethod-1').change(function(){
if ( $(this).is(':checked') == true ) {
teardown();
}
});
$('input#paymentmethod-2').change(function(){
if ( $(this).is(':checked') == true ) {
setup();
}
});
function setup() {
if (btInstance) {
return;
} else {
var client_token = "<ps:braintreetoken />";
braintree.setup(client_token, "dropin", {
container: "bt-dropin",
onReady: function (bt) {
btInstance = bt;
}
});
}
}
function teardown() {
if (!btInstance) {
return;
}
btInstance.teardown(function () {
btInstance = null;
});
}
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
Drop-in UI is still loaded when you select the Lastschrift payment option, which is why you're receiving the validation errors.
One way to avoid these validation errors is to use the 'teardown' method in the 'onReady' callback in braintree.js to remove the Drop-in UI if a customer selects Lastschrift.
Alternatively, you can separate each of these payment methods into entirely different form elements on your page.

jQuery post within post done function

I'm trying to implement and figure out something that I've never done before. I have a sense how to do it but I'm not exactly sure how to do so...
So I have a button on my website where users perform authorization of my application. When user goes to xx website and authorizes my application I would like to perform a jQuery post to this xx website every 3 seconds checking whether the user has performed authorization of my app to use it.
If the response from the website is success i'd like to make the button enabled and clickable to proceed to final step to insert some record into the DB.
So the current code looks like this:
$(document).on("click", "#btnClick", function (e) {
$(this).prop('disabled', true);
e.preventDefault();
$.post("/GetMyData/GenerateSession")
.done(function (sessionID) {
window.open("https://example.com/Authorize?=" + data, "_blank");
$('#btnClick').hide();
$('#btnAuthorize').show();
$("#step2").removeClass("disabled").addClass("selected");
});
});
So as you can see when SessionID is generated in my aciton, I simply open up a new tab in my browser and take him to the corresponding website.
Now what I'd like to do in final step is remove this code where user himself has to click the button to authorize the application like this:
$(document).on("click", "#btnAuthorize", function () {
$.post('/GetMyData/StoreToken')
.done(function (data) {
if (data.result == "Success") {
window.location.href = '/Success';
}
});
});
So without having the user to perform this final step. I'd like to make my application do this for user and perform a post every 3 seconds once he #btnClick even has been triggered..
How could I do this with jQuery?
P.S. I'd like to do this because I've noticed that some people simply don't authorize the application for usage but still press this button ,and then errors occur, which is why I'd like to disable usre clicking this button unless he indeed authorized the app.
Something like this should do it.
var r = window.setInterval(function(){
$.post('/GetMyData/StoreToken')
.done(function (data) {
if (data.result == "Success") {
window.location.href = '/Success';
}
});
},3000);
If you want to perform some function every X time you have to use setTimeout/setInterval functions of javascript (https://www.w3schools.com/jsref/met_win_settimeout.asp)

Can I send an alert from the server to the client in Meteor?

is there a way I can sent an alert from the server to the client? For example, a user clicks a button. That button calls a method on the server that checks if the user has been assigned an ID# yet. If the user has not been assigned an ID#, I want the browser to get an alert. I could easily do a check if I publish the ID# to the client, but the ID# is very sensitive and so I don't want to publish it. Any thoughts? Thank you in advance.
You can try something like the following:
1) On the client, create a button click listener that runs a Meteor method.
// CLIENT
Template.example.events({
'click button': function () {
Meteor.call('checkIfUserHasId', function (err, userHasId) {
if (!userHasId) {
alert('user has no id');
}
});
}
});
2) On the server, create the Meteor method that checks if the user has an id.
// SERVER
Meteor.methods({
checkIfUserHasId: function () {
// check if user has id
return true; // or false depending whether user has id or not
}
});
Meteor methods can be called remotely on the client but are defined on the server. This should help achieve what you want in terms of not exposing the id's when performing the check.

how to force redirect to login page in javascript

I am building a website where I want users to have to log in to be able to view a certin page (kn this case it is called gallery.php) I implemented some code I found on this site, which redirects the user back to the login page when they click on the gallery link in the menu. However when I log in, and get redirected to the gallery again, the website does not acknowledge that I have logged in and redirects me back to the login page again. I am aware that questions like this have been asked before, but any help would be appreciated. My code is bellow
//from login.html
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.id.value=="Admin") {
if (form.pass.value=="rycbar123") {
var sessionTimeout = 1; //hours
var loginDuration = new Date();
loginDuration.setTime(loginDuration.getTime()+(sessionTimeout*60*60*1000));
document.cookie = "SistaDansenSession=Valid; "+loginDuration.toGMTString()+"; path=gallery.php";
location="gallery.php"
} else {
alert("Invalid Password")
}
} else { alert("Invalid UserID")
}
}
//from gallery.php
<!--force login code-->
<script type="text/javascript">
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1) {
alert("You must be logged in to view this page")
location.href = "login.html";
}
else {
alert("login succesful")
} </script>
Thanks so much
Try changing:
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1)
to
if (document.cookie.indexOf("SistaDansenSession") < 0)
When you set the cookie, you are setting the cookie attribute 'SistaDansenSession' equal to the value 'Valid'. In your original code, you are attempting to retrieve a cookie attribute 'SistaDansenSession=Valid', whereas the attribute you want to retrieve is just 'SistaDansenSession'. When the cookie is set, the attribute exists, so it will have an index that is >= 0. In that case, the redirect to the login does not occur - which I think is your desired behavior.

Simple example of popup authentication with Facebook Graph API

Trying to get Facebook to authenticate my users via a javascript popup. Right now, I have:
<input type="button" value="Connect with Facebook" onclick="window.open('https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXX&redirect_uri=http://example.com/step2&display=popup')" />
But when the user logs in via Facebook, the popup just displays the Facebook.com homepage. I'd like for the popup to authenticate the user and go away so that I can start retrieving user data from the graph api.
Is there a better / easier way to do this? Simple examples are appreciated.
Thank you.
oauth2 in facebook involves two steps, call authorize to get code, then call access_token to get token.
One way to deal with the pop login:
open login url in new window just like you did,when the facebook redirects back to your url in the popup, you set the cookie either through server side code or using javascript to capture url query parameter, when page is loaded in the popup, close the window immediately window.close.
On your main page, after your window.open code, add JavaScript code to detect if popup is closed and capture the cookie:
var signinWin;
$('#FacebookBtn').click(function () {
var pos = screenCenterPos(800, 500);
signinWin = window.open("[URL]", "SignIn", "width=780,height=410,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0,left=" + pos.x + ",top=" + pos.y);
setTimeout(CheckLoginStatus, 2000);
signinWin.focus();
return false;
});
function CheckLoginStatus() {
if (signinWin.closed) {
$('#UserInfo').text($.cookie("some_cookie"));
}
else setTimeout(CheckLoginStatus, 1000);
}
Why not simply...
function authorizeAppInPopup() {
FB.login(function(response) {
if (response.authResponse) {
// User authorized app
} else {
// User cancelled login or did not fully authorize
}
}, {scope: 'publish_stream'});
}
??? : ]
https://developers.facebook.com/docs/reference/javascript/FB.login/
Checkout this article: Create Facebook PopUp Authentication Window using PHP and javascript for customize popup authentication.
It might be a good idea to do both a callback function from the Child window as Avner says as well as a timer that watches for the window to be closed. That way if the Child window is closed without a specific action you can take appropriate action on the Parent window.
**On Child**
// Set oAuthToken from server side when it comes back from authenticating
// and you have the token on the server side.
var oAuthToken = "";
oAuthToken = "--STRING INSERTED BY SERVER SIDE CODE--";
window.opener.pbFromPopup(oAuthToken);
**On Parent :**
function CheckLoginStatus() {
if (authWindow.closed) {
// Handle error if authentication window is closed
// without any action on Allow or Deny
alert("window closed");
//location.href = "errorPage.aspx?error=authwinclosed;
}
else setTimeout(CheckLoginStatus, 1000);
}
function pbFromPopup(token) {
// Function called from child window,
// token is passed back from child
authWindow.close();
// Put token in a hidden form field and submit the form to pass
// it back to the server
$("#authToken").val(token);
$("#form1").submit();
}

Categories