why my alert shows undefined in javascript - javascript

var database = require('../../db');
var rightponame = '1';
var rightdevname = '';
var rightpopassword = '';
var rightdevpassword = '';
database.db.once('open', function() {
console.log('success');
var cursor = database.db.collection('user').find({}, {
_id: 0
});
cursor.each(function(err, doc) {
if (doc != null) {
rightponame = doc.productOwner;
rightdevname = doc.developer;
rightpopassword = doc.popassword;
rightdevpassword = doc.devpassword;
console.log(rightponame);
console.log(rightdevname);
console.log(rightpopassword);
console.log(rightdevpassword);
} else {
console.log('o');
}
});
});
function login() {
var getusername = document.getElementById("username").value;
var getpassword = document.getElementById("password").value;
alert(rightponame);
}
Finally, I get rightponame, rightdevname, rightpopassword and rightdevpassword value. But in the login function, I get undefined in the alert.
Why?

In JavaScript, alert is only available in the browser. It appears you're using node.js or the like. Try console.log instead, as you're doing on db open.
Then when you check the terminal window where the process is running, you should see the value of console.log.
Since console.log takes multiple values, it's helpful to prefix with something distinguishable like:
console.log('<<<<<<<', rightponame)

Related

Trying to use sessionStorage in javascript

I'm trying to show a popup window only once per session. In order to achieve that I'm using sessionStorage function. however, the popup is showing up whenever I reload the web page. Can you please let me know where I'm making the mistake.
dialogue = new IMu.App.Dialogue();
dialogue.setHtmlMessage(IMu.string('dialogue-heading'));
dialogue.show({ showDetails: true });
window.sessionStorage.setItem('message','true');
var is_dialogue = window.sessionStorage.getItem('message');
if (is_dialogue != 'true')
{
dialogue.show();
}
Below is the show function
show: function(options, callback)
{
if (typeof(options) == 'function')
{
callback = options;
options = undefined;
}
var test = jQuery('body').children('div.imu-dialogue');
jQuery('body').children('div.imu-dialogue').remove();
var owner = self.owner = jQuery('body').child('div', 'imu-dialogue');
var box = owner.child('div', 'box');
var message = box.child('div', 'message');
if (this.message)
{
var value = this.message.value;
var method = this.message.type;
message[method](value);
}
if (self.details)
{
var details = box.child('div', 'details');
for (var i in self.details)
{
if (! self.details.hasOwnProperty(i))
continue;
var detail = details.child('div', 'detail');
var value = self.details[i].value;
var method = self.details[i].type || 'text';
detail[method](value);
}
var show = box.child('div', 'show-details');
if (! options || options.showDetails !== true)
{
show.text('Details');
details.hide();
}
else
{
details.show();
show.text('I agree');
}
show.on('click', function()
{
self.owner.remove();
});
}
You've got your logic backwards. You need to check if the sessionStorage item has been set first. If it has not been set, show the dialog and then set it.
if (!sessionStorage.getItem('notified')) {
let dialogue = new IMu.App.Dialogue();
dialogue.setHtmlMessage(IMu.string('dialogue-heading'));
dialogue.show({ showDetails: true });
sessionStorage.setItem('notified', 'true');
}
There is no need to check the value of the stored property. Simply testing for it's existence is enough.
Forget the dialogue.show();
If you try in a new tab of your browser the following code:
window.sessionStorage.setItem('message','true');
is_dialogue = window.sessionStorage.getItem('message');
is_dialogue != 'true' // false
refresh the page and run
is_dialogue = window.sessionStorage.getItem('message');
is_dialogue != 'true' // false
You may have something in your code whick clean session storage on mounted or on created ?

Call functions from sources directly in Chrome console?

For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91

localStorage Overwritten/ and innerHTML fail

On the 14th and 28th line, it's not changing the text of the label tag and on the recorForm or loginSetup, data is overwritten. I tried loop with .key, but it outputed the wrong stored results and I'm not sure what I did wrong. so I'm leaving it at this. What I want to know is why the innHTML of the label won't change.(I assume it's due to loading)
window.onload = alert('Window Loaded');
function recordForm() {
var userMail = document.getElementById('email').value;
var userPass = document.getElementById('password').value;
var confirm = document.getElementById('confirmation').value;
var text = document.getElemetsByClassName('errorText');
//Check that the email is not taken and confirm validation
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail.value);
localStorage.setItem('passwordz', userPass.value);
} else {
text.innerHTML = 'Password does not match!'; //line 14
}
}
function loginSetup() {
var mail = localStorage.getItem('emailz');
var pass = localStorage.getItem('passwordz');
var mailInput = document.getElementById('logEmail').value;
var passInput = document.getElementById('logPassword').value;
if ((mailInput === mail) && (passInput === pass)) {
alert(mail);
alert(pass);
} else {
text.innerHTML = 'Invalid login'; //line 28
alert('no dice');
alert(mail);
alert(pass);
}
}
You should try to store userMail.value and userPass.value. Both yet are already the values:
var userMail = document.getElementById('email').value; //Those are values already
var userPass = document.getElementById('password').value; //Those are values already
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail); //Remove the .value
localStorage.setItem('passwordz', userPass); //Remove the .value
}
Also getElementsByClassName returns a collection, thus you want to select the first item of it (assumably):
var text = document.getElemetsByClassName('errorText'); //Misstyped and no index.. wont work
var text = document.getElementsByClassName('errorText')[0]; //Should work
var text = document.querySelector('.errorText'); //Would prefer that one
At last in the function loginSetup() you have to redefine text:
var text = document.querySelector('.errorText');

Can't update javaScript global variable

Here I have global variable userId, and i want to update it inside signInUserFunction(), to use is in other function. I have tried to define it using var, window, But all these didn't help. This variable doesn't update. As i see its about AJAX async. So, what can i do with it?
And yes, I know that its not good to make authentication with JS, I am quite new to it. So, I am just creating random methods to improve.
var userId = 1;
function signInUser() {
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data) {
var items = [];
var i = 0;
$.each(data, function(firstname, value) {
var str = JSON.stringify(value);
data = JSON.parse(str);
var innerId;
for (p in data) {
innerId = data[p].id;
if ($('#nameSignIn').val() == data[p].first_name && $('#passwordSignIn').val() == data[p].password) { //
userId = innerId;
window.location.href = "content.html";
break;
} else {
i++;
if (i == data.length) {
alert("Ощибка в логине или пароле!")
}
}
}
});
});
}
How are you determining whether or not it has been set? It looks like immediately after you set it, you navigate to a different page. When you get to that page, you will have an entirely new window.
Try alerting the value before navigating away.
EDITED: Here is how you could pass it to the other page (but you shouldn't do this in a real app)
window.userId=innerId;
alert(window.userId);
//this isn't a very secure way to do this. I DON'T recommend this
window.location.href = "content.html?id=" + innerId ;
Then in the other page, you could access it off the document.location:
alert(document.location.toString().split("?id=")[1]);
After reading my comments, you may want to try this:
var userId = 1;
function signInUser(){
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data){
var items = [], actors = data.Actors, l = 0;
$.each(actors, function(i, o){
l++;
if($('#nameSignIn').val() === o.first_name && $('#passwordSignIn').val() === o.password){
userId = o.id;
// this will redirect before any other code runs -> location = 'content.html';
if(l === actors.length){
alert('End of Loop');
}
}
});
});
}
signInUser();
I would not store sensitive data in JSON such as passwords. Use a database. There is no need to get all the data at the same time either.
Using the idea #mcgraphix proposed (and giving you the same warning...this would certainly not be the way to transfer data like this in a production environment), here is one way to do it:
function signInUser() {
var url = 'http://localhost:8887/JAXRSService/webresources/generic/getAllUsers';
var userId;
$.getJSON(url, function(data) {
$.each(data.Actors, function(index, actor) {
// Cache the values of the #nameSignIn and #passwordSignIn elements
var name = $('#nameSignIn').val();
var password = $('#passwordSignIn').val();
if (actor.first_name === name && actor.password === password) {
// We have found the correct actor.
// Extract its ID and assign it to userId.
userId = actor.id;
window.location.href = "content.html?userId=" + userId;
}
});
// This alert should only be reached if none of the actor objects
// has a name and password that matches your input box values.
alert("Ощибка в логине или пароле!");
});
}
// On the next page...
// Top answer from http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
// This approach can handle URLs with more than one query parameter,
// which you may potentially add in the future.
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
var userId = getQueryVariable('userId');
Thanks you for help.Ended it all with usage of:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

Deleting a record from desktop Chrome IndexedDB vs from android Chrome IndexedDB

I am trying to delete a record from IndexedDB using the fallowing code:
DB.indexedDB.IDBTransaction.READ_WRITE="readwrite";
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB;
if ('webkitIndexedDB' in window) {
window.IDBTransaction = window.webkitIDBTransaction;
window.IDBKeyRange = window.webkitIDBKeyRange;
DB.indexedDB.IDBTransaction.READ_WRITE=IDBTransaction.READ_WRITE;
}
DB.indexedDB.idelete = function( storeName, indexValue, index, keyPathfield ){
var db = DB.indexedDB.db;
var transaction = db.transaction([storeName], DB.indexedDB.IDBTransaction.READ_WRITE);
var store = transaction.objectStore(storeName);
var sindex = store.index(index);
sindex.get(indexValue).onsuccess = function (event){
store.delete(event.target.result[keyPathfield]).onsuccess = function(event) {
document.getElementById("result").innerHTML+="deleted<br>";
};
}
}
it calls onsuccess but when I add a new record with the same indexValue and call idelete again and search for the record using the fallowing code:
DB.indexedDB.readAll=function(storeName, index){
var results=document.getElementById("result");
var db = DB.indexedDB.db;
var transaction = db.transaction([storeName]);
var store = transaction.objectStore(storeName);
var key = IDBKeyRange.lowerBound(0);
var cursor = store.openCursor(key);
var x=0;
cursor.onsuccess = function(event){
var result = event.target.result;
if(result)
{
x++;
var charx=x.toString();
results.innerHTML+=charx+result.value[index]+"<br>";
result.continue();
}
else
return;
}
if I am using Windows Chrome, the record is deleted correctly. But if I am using Android Chrome version M18.1, readAll can still find the record but idelete can't delete it because it was actually deleted.
How about just open key cursor instead of actually retrieving it.
sindex.openKeyCursor(indexValue).onsuccess = function (event){
var cursor = event.target.result;
if (cursor) {
// cursor.delete();
var key = cursor.key;
var primaryKey = cursor.primaryKey;
store.delete(primaryKey).onsuccess = function(event) {
document.getElementById("result").innerHTML+= key + ' (' + primaryKey + ") deleted<br>";
};
}
} else {
document.getElementById("result").innerHTML+= indexValue + ' not found.<br>";
}
}
The problem here is that there are multiple transactions in flight at once - I can tell this becuause idelete() doesn't return the transaction it creates, so there's no way to guarantee that readAll() executes after idelete().
instead you're going to need to make idelete() return the transaction, and then handle that:
foo = idelete(....).oncomplete = function() { readAll()...}
I think the fact that it happens to work in android is just a fluke of the implementation of chrome (which is single-process on android, so events tend to run more serially there)

Categories

Resources