Navigation within a phonegap application - javascript

I am playing around with the local storage on PhoneGap, trying to create a JavaScript login. My current problem is when I run the application, it will not go to the main menu if the username and password is correct.
I believe the problem is with the window.location.href method. I want to navigate to a local page, not an online one.
Van anyone suggest another way to do this?
$(document).ready(function() {
if (typeof(localStorage) === 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
$("#return_form2").submit(function(){//load the items
getItems();
});
}
});
var getItems = function() {
var timeLog, logLength, i;
i = 0;
logLength = localStorage.length-1; //how many items are in the database starting with zero
timeLog = '';
// loop through each item in the database
for (i = 0; i <= logLength; i++) {
var itemKey, value, values, firstname, password, email;
//variables for the key and values
itemKey = localStorage.key(i);
value = localStorage.getItem(itemKey);
values = JSON.parse(value);
firstname = values.fname;
password = values.pass;
email = values.email;
course = values.class;
var tt = course;
var un = document.return_form2.username.value;
var pw = document.return_form2.password.value;
var web = "Web Systems Development";
if ((un == firstname) && (pw == password) && (tt == web)){
window.location.href = "AppMenu.html";
return false;
}
else {
alert ("Incorrect Password");
}
}}

I'm not sure that ((un == firstname) && (pw == password) && (tt == web)) is true, anyway, the next line worked for me
window.location="AppMenu.html";
Also you don't have to return false

Related

google tag manager template only reading first elements of array for events with more than 1 item

I'm implementing this google tag manager template(GA3/UA) but the issue is that when there is more than 1 product, it only catches or reads the first element of the arrays, this happens for all the events that can have more than 1 product, I'm kinda new to this, can anyone guide me in why is this happening? here is the code for the sandbox javascript, I just need to get all the elements of the arrays, not the first one, everything else works fine. Thank you very much in advance.
___SANDBOXED_JS_FOR_WEB_TEMPLATE___
const log = require('logToConsole');
const makeTableMap = require('makeTableMap');
// Call APIs to set dataLayer and copy values from dataLayer
const copyFromDataLayer = require('copyFromDataLayer');
// Set the function where we want to push the dataLayer
const createQueue = require('createQueue');
const dataLayerPush = createQueue('dataLayer');
//Validate structure
var ecommerce_data = copyFromDataLayer('ecommerce.'+data.activity);
if(ecommerce_data == undefined){
//dataLayerPush({'event': "error", "info": "enhanced ecommerce base structure not found for "+ data.activity});
// return;
ecommerce_data = {};
}
var ecommerce_actionField = copyFromDataLayer('ecommerce.'+data.activity+".actionField");
if(ecommerce_actionField == undefined){ ecommerce_actionField = {};}
var ecommerce_products = copyFromDataLayer('ecommerce.'+data.activity+".products");
if(ecommerce_products == undefined){ecommerce_products = []; ecommerce_products.push({});}
var ecommerce_impressions = copyFromDataLayer('ecommerce.'+data.activity);
if(ecommerce_impressions == undefined){ecommerce_impressions = []; ecommerce_impressions.push({});}
var ecommerce_promotions = copyFromDataLayer('ecommerce.'+data.activity+".promotions");
if(ecommerce_promotions == undefined){ecommerce_promotions = []; ecommerce_promotions.push({});}
//this fucntion works only for one element edition.
//Usable for: actionFiel, product click, detail, add, remove, promotionClick
//Params: aField, ecommerce_origin
function merge_element() {
log("entro 1");
let key;
for (key in arguments[0]) {
arguments[1][key] = arguments[0][key];
}
return arguments[1];
}
//this fucntion works for a list of elements edition.
//Usable for: products, impressions and promotions
//Params: prods, ecommerce_origin, type_index
function merge_elements(){
if(arguments[2] == "all"){
let key, elem;
for(elem in arguments[1]){
for (key in arguments[0]) {
arguments[1][elem][key] = arguments[0][key];
}
}
}else{
var indexes = data.index.split(",");
log("indexes", indexes);
let elem, key;
for(elem in indexes){
if(!arguments[1].hasOwnProperty(indexes[elem]-1)){
log(indexes[elem] + " is not a number or not beyong your array size");
continue;
}
for (key in arguments[0]) {
arguments[1][indexes[elem]-1][key] =arguments[0][key];
}
}
}
return arguments[1];
}
var aField = {}, prods = {}, impr = {},prom ={};
if(data.actionField != undefined){aField = makeTableMap(data.actionField, 'key', 'value');}
if(data.products != undefined){prods = makeTableMap(data.products, 'key', 'value');}
if(data.impressions != undefined){impr = makeTableMap(data.impressions, 'key', 'value');}
if(data.promotions != undefined){prom = makeTableMap(data.promotions, 'key', 'value');}
var type_index = "all";
if(data.type_index != undefined){type_index = data.type_index;}
const datalayer = {};
datalayer[data.activity] ={};
datalayer.currencyCode = copyFromDataLayer('ecommerce.currencyCode') != undefined? copyFromDataLayer('ecommerce.currencyCode'): data.currencyCode;
if(data.activity == "checkout"||data.activity =="click"||data.activity =="detail"|| data.activity == "purchase"){
log("entro click");
datalayer[data.activity].actionField = merge_element(aField, ecommerce_actionField);
datalayer[data.activity].products = merge_elements(prods, ecommerce_products, type_index);
}
if(data.activity == "add"||data.activity == "remove"){
datalayer[data.activity].products = merge_elements(prods, ecommerce_products, type_index);
}
if(data.activity == "promoView"|| data.activity == "promoClick"){
datalayer[data.activity].promotions = merge_elements(prom, ecommerce_promotions, type_index);
}
if(data.activity == "impressions"){
datalayer[data.activity].impressions = merge_elements(impr, ecommerce_impressions, type_index);
}
//basic data recompilation
var event = "", eventCategory = "",eventAction = "",eventLabel = "",eventValue = 0;
if(data.basic_data){
event = data.event_name +"";
eventCategory = data.event_category+"";
eventAction = data.event_action+"";
eventLabel = data.event_label+"";
eventValue = data.event_value+"";
}
if(event == ""){
event = copyFromDataLayer('event')+ "_changed";
}if(eventCategory == ""){
eventCategory = copyFromDataLayer('eventCategory') != null? copyFromDataLayer('eventCategory'): "Enhanced ecommerce";
}if(eventAction == ""){
eventAction = copyFromDataLayer('eventAction') != null? copyFromDataLayer('eventAction'): data.activity;
}if(eventLabel == ""){
if(copyFromDataLayer('eventLabel') != null){
eventLabel= copyFromDataLayer('eventLabel');
}else{
if(data.activity == "impressions"){
eventLabel = datalayer[data.activity].impressions[0].name;
}
if(data.activity == "promoView"|| data.activity == "promoClick"){
eventLabel = datalayer[data.activity].promotions[0].name;
}else{
eventLabel=datalayer[data.activity].products[0].name;
}
}
}if(eventValue == 0){
if(copyFromDataLayer('eventValue') != null){
eventValue = copyFromDataLayer('eventValue');
}
}
dataLayerPush({'event': event,'eventCategory': eventCategory, 'eventAction': eventAction, 'eventLabel': eventLabel, 'eventValue': eventValue,'ecommerce':datalayer});
data.gtmOnSuccess();
You can Mock the DL values in the template unit tests.
Mock it properly, run the tests, debug the values. If that is not enough to make the issue obvious, post a mcve of your attempt.
Don't just dump the whole template in a question. Show your debugging attempts.

validation login with data stored on localStorage

the code i made only reads the last index from localStorage for login validation, can someone help to login using all existing data?
$('#btnlogin').click(function(){
var usernamelogin = $('#usernamelogin').val()
var passwordlogin = $('#passwordlogin').val()
var data_user1 = JSON.parse(localStorage.getItem('data_user'))
for(var i in data_user1){
var entry = data_user1[i]
}
if(usernamelogin == entry.username && passwordlogin == entry.password){
alert("Log in successfull")
window.location.href = "curhat.jsp"
}else{
alert("wrong username or password")
}
//console.log(data_user1)
//console.log('username = ' + entry.username)
})

Multiple Redirects based off Dropdown Answers in Form

I'm struggling to find an answer to this and have tried a few things, but I'm hoping someone can help me out. I have a form on a Landing Page that redirects a submission to a disqualifying thank you page if the lead answers one of the questions incorrectly. I know the code I have works well in most cases but one of the questions has multiple answers that would disqualify a lead and it will only disqualify if they choose one option but not the other option that would ALSO disqualify that person.
For example, we have a dropdown selection that lets you choose your age range. If you choose "30-49" it needs to disqualify that person, which it does currently but I also need it to disqualify someone for choosing "65 and over" as well. Right now it will redirect to our disqualifying page if they choose "30-49" but it won't redirect if they choose "65 and over". I need it to do both.
I've tried adding the AND&& tag in my code instead of the OR|| tag but I'm still struggling to get it to work. Any help with this would be much appreciated. Thank you in advance!
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var months_12 = getUrlVars()["months_12"];
var doctor_care = getUrlVars()["doctor_care"];
var current_benefits = getUrlVars()["current_benefits"];
var have_attorney = getUrlVars()["have_attorney"];
var first_name = getUrlVars()["first_name"];
var last_name = getUrlVars()["last_name"];
var age = getUrlVars()["age"];
var email = getUrlVars()["email"];
var phone_number = getUrlVars()["phone_number"];
var redirect_url = '';
if (months_12 == "No" || doctor_care == "No" || current_benefits == "Yes" || have_attorney == "Yes" || age == "30-49" || age == "65 and over") {
redirect_url = "http://unbouncepages.com/mblsdd-thank-you-3/?";
}
else {
redirect_url = "http://unbouncepages.com/mblssd-thank-you-5/?";
}
redirect_url = redirect_url+"months_12="+months_12+"&doctor_care="+doctor_care+"&current_benefits="+current_benefits+"&have_attorney="+have_attorney+"&age="+age+"&first_name="+first_name+"&last_name="+last_name+"&email="+email+"&phone_number="+phone_number;
window.location.href = redirect_url;
</script>
Query strings in most modern browsers will automatically be encodeURI()'ed. This means you must decodeURI() the query string value. Also, you don't need to call the queryString() function for each key/value pair you need. Ex:
function queryString()
{
let vars = {};
let parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value)
{
vars[key] = decodeURI(value);
});
return vars;
}
const queryArray = queryString();
let months_12 = queryArray["months_12"];
let doctor_care = queryArray["doctor_care"];
let current_benefits = queryArray["current_benefits"];
let have_attorney = queryArray["have_attorney"];
let first_name = queryArray["first_name"];
let last_name = queryArray["last_name"];
let age = queryArray["age"];
let email = queryArray["email"];
let phone_number = queryArray["phone_number"];
let redirect_url = "";
if(months_12 == "No" || doctor_care == "No" || current_benefits == "Yes" || have_attorney == "Yes" || age == "30-49" || age == "65 and over") {
redirect_url = "http://unbouncepages.com/mblsdd-thank-you-3/?";
}
else {
redirect_url = "http://unbouncepages.com/mblssd-thank-you-5/?";
}
redirect_url = redirect_url+"months_12="+months_12+"&doctor_care="+doctor_care+"&current_benefits="+current_benefits+"&have_attorney="+have_attorney+"&age="+age+"&first_name="+first_name+"&last_name="+last_name+"&email="+email+"&phone_number="+phone_number;
window.location.href = redirect_url;
If you try to get the value of a non-exsistant key then you will get 'undefined'.

Comparing user sign up info in an array with user login input

I have two buttons: a sign up and a log in. I intend to collect the input form values from the sign up into an array (this works). I then want to compare the user input from the sign up with the user input from the login and notify the user that they are logged in. (I am yet to get started with localStorage and JSON. I want to get this done using arrays first).
I have tried using a for loop and if statements with logical operators (&&).
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
var custData = [];
custData.push(custName, custEmail, custPass);
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
for (var i = 0; i < custData.length; i++) {
if ((currentName === custData[0]) && currentEmail === custData[1] && currentPass === custData[2]) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
}
};
});
});
May be you could try only IF statement without the loop.
The following thing checks if there is such item in the array and if it IS, will do smth:
if (custData.indexOf(currentName) != -1
&& custData.indexOf(currentEmail) != -1
&& custData.indexOf(currentPass) != -1) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
I have been learning about localStorage. I decided to use it on this task. I collected the values that the user inputs when signing up, and 'saved' them on local Storage. I then collected the value the user inputs and 'retrieved' them via local Storage. Here is the code:
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
localStorage.setItem("name", "Raych") +
localStorage.setItem("email", "raych#gmail.com") +
localStorage.setItem("password", "hey"); ;
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
event.PreventDefault;
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
localStorage.getItem("name") +
localStorage.getItem("email") +
localStorage.getItem("password");
$("#userLogIn").text("You are logged in!");
});
});

How to retrieve data from local storage in javascript?

I'm making a hangman game and would like to store and retrieve the person's score and their username from the local storage and display it on the leader board div. How do I do this? I've seen most people use localStorage.get and localStorage.set but I'm not sure how to implement it here.
Thanks for the help.
This is my javascript code so far:
function storeUserDetails() {
var userObject = {};
userObject.name = document.getElementById("nameinput").value;
userObject.username = document.getElementById("usernameinput").value;
userObject.password = document.getElementById("passinput").value;
userObject.repeatpassword = document.getElementById("repeatpassinput").value;
userObject.topscore = 0;
localStorage[userObject.username] = JSON.stringify(userObject);
document.getElementById("result").innerHTML = "<b>Registration
Successful<br> Please <a href = '../PHP/login.php'><font color =
'orangered'>login</font></a></b>";
}
function checkLogin() {
if (localStorage.loggedInUsername !== undefined) {
var userObj = JSON.parse(localStorage[localStorage.loggedInUsername]);
}
}
function login() {
var username = document.getElementById("usernameinput").value;
if (localStorage[username] === undefined) {
document.getElementById("result").innerHTML = "<b>Username not found. Please sign up.</b>";
return;
} else {
var userObj = JSON.parse(localStorage[username]); //Convert to object
var password = document.getElementById("passinput").value;
if (password === userObj.password) {
localStorage.loggedInUsername = userObj.username;
document.getElementById("result").innerHTML = "";
window.location = "loggedin.php";
/*sessionStorage.setItem('status', 'logged in');*/
} else {
document.getElementById("result").innerHTML = "<b>Password incorrect. Please try again.</b>"
}
}
}
function updateScore() {
rankingTable = document.getElementById("leaderboardcontainer");
tableData = document.getElementById("content");
//Username and score to be displayed here.
}
You should use getItem, setItem and removeItem methods as shown in the documentation.
https://developer.mozilla.org/it/docs/Web/API/Window/localStorage

Categories