Javascript: User Authentication JSON Error - javascript

I'm making a login page for my web application, and I'm using a temporary data storage (I know this is not safe) for user verifiation. I'm trying to compate the username input to the data (only correct email is needed at the moment to get it working), but it's not working at all. I'm not getting an error message, just the alert that the username is not correct. It now displays both the user input and data, so I can see that my input is correct. What's wrong with it?
Thanks in advance!
(The data/object is in a seperate js file)
var count = 2;
function validate() {
var un = document.login.username.value; /* Username Input variable*/
var pw = document.login.password.value; /* Password Input variable*/
var valid = false;
let data = responseData;
for(var account in data.accounts){
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
console.log("Yes");
break;
}
}
if (valid) {
alert("Login was successful. Welcome, " + un + ".")
window.location = "https://www.google.com";
return false;
}
if (count >= 1) {
alert("The correct username is " + item_name + ", you put in "+un);
count--;
}
var responseData = {
authenticatUser: {
"ERR":0,
"RSP":{
"AUTHC":"true",
"USR":{
"ID":"2",
"TJT":"FULL",
"ACTV":"true",
"BO":"1489760664786",
"CONT":{
"FNM":"John",
"LNM":"Doe",
"PHN":"5556667777",
"PHNTP":"NONE",
"EML":"ex#mple.com",
"EMLTP":"NONE"
},
"ADMIN":"false",
"LLOGN":"1489760664786",
"ACCT":{
"ID":"2",
"TJT":"ID"
}
}
}
},

When you write:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
You are initializing a new valid variable that is only seen in that function. When you later access it outside the function you are seeing the original valid you initialized in line 5. This is called shadowing and it's a common source of bugs.
Do this instead:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
valid = true;
Now you should be changing the original valid variable.

Related

TypeError: Cannot find function getSheetById in object Spreadsheet

I want to have an automatic email machine, without having to write all of the messages and email addresses myself.
I'm really new to this, so please don't be too harsh.
function sendOrder() {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Are you sure you want to send the order?',
ui.ButtonSet.YES_NO);
var deliveryDate = ui.prompt('Delivery date:');
// Process the user's response.
if (response == ui.Button.YES) {
var s = SpreadsheetApp.getActive().getSheetById('1pON34oXVhlpC8goyBxfu6-Gw92tgQBUVUpskZUtgp4E');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveSheet().getDataRange();
var range = s.getRange('A1:C102');
var to = "example#example.com";
var body = '';
var htmlTable = SheetConverter.convertRange2html(range);
var body = "Here is the table:<br/><br/>" +
htmlTable +
"<br/><br/>The end."
MailApp.sendEmail(to, 'Subject', body, {
htmlBody: body
});
};
SpreadsheetApp.getUi().alert('Yeah! Your order has been sent :)');
}
I just expect this to give me a box to enter a date, once the date is entered it should say it has sent and our supplier will see all of the orders.
Issue:
This is because function getSheetById() does not exist.
Solution:
Use openById() instead:
var s = SpreadsheetApp.openById('yourIdHere');
Reference:
openById()
you need to add the function getSheetById(id):
function getSheetById(id) {
return SpreadsheetApp.getActive().getSheets().filter(
function(s) {return s.getSheetId() === id;}
)[0];
}

localStorage is saved but cannot retain data on browser after web page reload

I am trying to save chat message on localStorage (or sessionStorage) and display on web page, I can found the key-value pair stored in Devtool -> application -> localStorage, the message value update everytime when user sends the message and display on web page. However the content gone everytime when page reload. How to solve this?
Also what I am encountering is the push() to save messages to array will replaces instead of adds value, not sure if these 2 issues are related. Thanks.
pug file
#test2(style='height:200px; width:200px; border:1px solid #ccc')
js file
$('#sendMessage').on('click', function() {
var msg = $('#message').val()
var messages = [];
console.log(typeof(messages)); //obj
messages.push(msg);
console.log(messages); //array value
if (localStorage) {
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
localStorage.setItem('username', $('#username').val());
localStorage.setItem('date', currentTime());
var cUser = localStorage.getItem('username');
var cMsg = localStorage.getItem('message');
var cTime = localStorage.getItem('date');
} else {
console.log('localStorage is not supported.');
}
document.getElementById("test2").innerHTML += "<div>" + cUser + " : " + cMsg + "</div>";
// Clear the field
$('#message').val('');
}); // End click
reload page lose data
// Send Message
$('#sendMessage').on('click', function() {
// get value
var username = $('#username').val();
var msg = $('#message').val();
var time = currentTime();
//check if localStorage works and create msgArray
if (!localStorage) {
console.log('localStorage is not supported.');
} else {
//check if there is existing message array in msgArray
var msgArray = localStorage.getItem('message');
//if there is NULL, setup msgArray = [], converts a JavaScript value to a JSON string
if (JSON.stringify(msgArray) == 'null') {
msgArray = [];
} else {
//else parses a JSON string, constructing the JavaScript value or object described by the string
msgArray = JSON.parse(msgArray);
}
}
//add new message object to msgArray
var newMsg = {
msg: msg,
username: username,
time: time
};
msgArray.push(newMsg);
// stringsfy the message and store it to localStorage
localStorage.setItem('message', JSON.stringify(msgArray));
// dispaly current messages
var cMsg = JSON.parse(localStorage.getItem('message'));
// console.log(cMsg); // should shows list of array with new added message objects
// for (var i = 0, max = cMsg.length; i < max; i++) {
//document.getElementById("test2").innerHTML += "<div>" + cMsg[i].username + " : " + cMsg[i].msg + " at " + cMsg[i].time + " </div>";
$('#test2').append('<div class="well well-sm">' + cMsg[cMsg.length - 1].username + ' : ' + cMsg[cMsg.length - 1].msg + ' <span class="pull-right"><small id="date"> at ' + cMsg[cMsg.length - 1].time + '</small></span></div>');
// load the bottom of message
var objDiv = document.getElementById("chatArea");
objDiv.scrollTop = objDiv.scrollHeight;
// Clear the field
$('#message').val('');
}); // End click
I am not sure what you are trying to accomplish with your for loop, since you seem to be setting the same value as many times as you have messages (essentially that's worth nothing, setting it once should be enough)
Let's revisit your steps:
You are getting a value from an input element with id message, and saving it into the msg variable
var msg = $('#message').val()
You construct a new array, and push it in
var messages = [];
messages.push(msg);
And then you iterate the array, but re-use the msg variable
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
So essentially, you did this:
localStorage.setItem('message', $('#message').val());
and nothing more. Maybe you wanted to get the array of messages first, and then add the new message to it, rather something like the following
function addMessage() {
// get the potential array
var messages = JSON.parse( localStorage.getItem('message') || '[]' );
// add the message
messages.push($('#message').val());
// save the array as a string, using JSON.stringify
localStorage.setItem('message', JSON.stringify( messages));
// empty the message value
$('#message').val('');
console.log(messages);
}
If you want to save some chat messages, I think you should make sure that all message are properly linked with the author's username and the time it was wrote.
You tried an array... For the messages, but not for the other infos.
And you misused the array.
LocalStorage will only store a string.
Well... I think it can store objects too... But It is a habit of mine to always store strings.
This way, it always can be console logged fast, instead of bugging...
So stringify the array before saving it.
And when you retreive it,you have to parse it back to an array to be able to push a new message into it.
Ok... So will you try to synchronize 3 or more arrays?
I suggest ONE array of objects.
Each objects containing all the relevant infos linked to a particular message.
See comments in code.
$('#sendMessage').on('click', function() {
// ...
var chatWindow = $("#chatWindow");
// Get all values now.
var msg = $('#message').val();
var username = $('#username').val();
var time = moment().format("hh:mm:ss");
if (!localStorage) {
console.log('localStorage is not supported.');
}else{
// Retreive previous messages
var messageArray = localStorage.getItem('message');
// If there was none, set it as an array
if(JSON.stringify(messageArray) == "null"){
console.log(JSON.stringify(messageArray));
messageArray = [];
// If there was, get them back from string to an array of objects.
}else{
messageArray = JSON.parse(messageArray);
}
// Set the new message object.
var newMsg = {msg:msg,
time:time,
username:username
}
// Insert the new message object in the array.
messageArray.push(newMsg);
// Save the array as a string.
var messagesStringified = JSON.stringify(messageArray);
localStorage.setItem('message', messagesStringified);
// I suppose that showing the messages from what is saved re-assures you about the saving...
var cMsg = localStorage.getItem('message');
// Empty chatWindow
chatWindow.empty();
// Loop through the messages.
var allMessages = JSON.parse(cMsg);
for(i=0;i<allMessages.length;i++){
chatWindow.append("<div>" +
allMessages[i].time +
" | "+ allMessages[i].username +
" : " + allMessages[i].msg + "</div>");
}
console.log(JSON.stringify(messageArray));
// Clear the field
$('#message').val('');
}
}); // End click
$('#clear').on('click', function() {
localStorage.clear();
});
Have a look on **CodePen.

Parse JSON using javascript and get specific value in array

In my console log the array look like this:
{"userid":"5502","fullname":"My fullname","email":"sample#yahoo.com","user_access":"real"}
Now on my ajax, I have a handle code for the data array that the server sends to the app:
function handleData(responseData) {
var access = responseData;
console.log(access);
if (access == '"real"') {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}
How I can get the specific value of this "user_access":"real" in array and use it in condition.
like this:
if (access == '"real"') { // What should be the format of access variable?
alert("Welcome");
location.href = "home.html";
}
function handleData(responseData) {
var response = JSON.parse(responseData);//assuming you are getting the response as a string
var access = response.user_access;
console.log(access);
if (access == "real") {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}//handleData()
Normally, we want our response to be in json ( or we can say 'object' ) form, so that we can easily access its inner properties. So, if it's already an object, you do not need to use JSON.parse. You can directly access any property like this - responseData.user_access . But if it's in string form, then you have to use JSON.parse() first to parse the string into JSON ( or object ) format.
If it is not surrounded by "" around the {} brackets then just do
function handleData(responseData) {
var access = responseData.access;
if (access === 'real') {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}

Code to populate lookup doesn't fully work first time

I have some javascript code on my form that when the record is first being created it auto populates 2 lookup fields with the current user. This works fine most of the time but I've noticed that on the first time that I use it (per day/session?) the first field that I want to fill in does get populated however the field still looks empty, as if the code has not worked.
I've confirmed that the field is getting filled in and it is only the display for this field that isn't working, but I can't figure out why, especially why it is only the one field that this is happening with.
I will post the code I use below, when calling it I pass in an array of the field names that I want to set. Can anyone help me find out why this isn't working?
Thanks
function RetrieveUserInfo(fieldsToSet) {
//Retrieve user information
var context;
var serverUrl;
var UserID;
var ODataPath;
context = Xrm.Page.context;
serverUrl = context.getServerUrl();
UserID = context.getUserId();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var retrieveUserReq = new XMLHttpRequest();
retrieveUserReq.open("GET", ODataPath + "/SystemUserSet(guid'" + UserID + "')", true);
retrieveUserReq.setRequestHeader("Accept", "application/json");
retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveUserReq.onreadystatechange = function () {
SetUserValues(this, fieldsToSet);
};
retrieveUserReq.send();
}
function SetUserValues(retrieveUserReq, fieldsToSet) {
if (retrieveUserReq.readyState == 4
/* complete */
) {
if (retrieveUserReq.status == 200) {
var retrievedUser = this.parent.JSON.parse(retrieveUserReq.responseText).d;
if (retrievedUser.FullName != null)
//Get details of current user
var setUservalue = new Array();
setUservalue[0] = new Object();
setUservalue[0].id = Xrm.Page.context.getUserId();
setUservalue[0].entityType = 'systemuser';
setUservalue[0].name = retrievedUser.FullName;
//get form type
var formType = Xrm.Page.ui.getFormType();
if (formType != undefined) { //Create
if (formType == 1) {
//for each field specified, set it to the current user
for (var i = 0; i < fieldsToSet.length; i++) {
Xrm.Page.getAttribute(fieldsToSet[i]).setValue(setUservalue);
}
}
}
}
else {
}
}
}
This is a long shot, but the field that doesn't work - it doesn't happen to be a disabled field? If it's a readonly field you might have to add
Xrm.Page.getAttribute(“fieldname”).setSubmitMode(“always”);
on the onsave event.

ajax post data error [object HTMLCollection]

I wrote this script to for a contact form on my website, everything works however instead of storing the data in me database all is get is
[object HTMLCollection] c
an anyone tell me what this is?
or what is going wrong? i have had a look on google but i cant find much information on it.
<script type="text/javascript">
//when the button is clicked
$(document).ready(function() {
$("#button").click(function() {
$('.small').hide();
var name = $("input#name").val();
if (name == "") {
$("span#name").show();
return false;
}
var name = $("input#email").val();
if (name == "") {
$("span#email").show();
return false;
}
var name = $("input#subject").val();
if (name == "") {
$("span#subject").show();
return false;
}
var name = $("textarea#message").val();
if (name == "") {
$("span#message").show();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "/scripts/send_message.php",
data: dataString,
});
$("#messagearea").load("console/new_message_profile.php?sent=1");
});
});
</script>
As #Namit mentioned, you use name as a variable everywhere. Building your string, email, subject and message are uninitialised.
They should give you an undefined - but no, due to a weird Internet Explorer behaviour (see Is there a spec that the id of elements should be made global variable?) these variables hold DOM elements. As you seem to have multiple elements with the same id (NEVER DO THAT), here a <span> and an <input>, the variables even seem to hold HTMLCollection objects. Which are casted to the string [object HTMLCollection], when you concat them with other strings.
You're reusing the variable name for all the other fields as well. You need to change the field name to the respective input id.
var name = $("input#email").val(); // needs to be email
var name = $("input#subject").val(); // needs to be subject

Categories

Resources