Read Gmail JavaScript API no work | Failed to execute 'atob' - javascript

I have a problem with displaying decrypted messages using the Gmail API, can someone help me and explain how to do it to make everything work properly.
The error that is displayed to me:
PS: Sorry for all grammar mistakes, i am not very advanced in English yet
I'm try decrypt messages using atob & i'm try split messages and use atob.
My HTML code:
<!--
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- [START gmail_quickstart] -->
<!DOCTYPE html>
<html>
<head>
<title>Gmail API Quickstart</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/mail-layout.css">
</head>
<body>
<p>Gmail API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<pre id="content2" style="white-space: pre-wrap;"></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" src="api.js"></script>
<script type="text/javascript" src="js-api/functions.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
<!-- [END gmail_quickstart] -->
api.js code:
// Client ID and API key from the Developer Console
var CLIENT_ID = '231998038190-410ifknsn879tle6uvmi8o0o3tlqtbt1.apps.googleusercontent.com';
var API_KEY = 'AIzaSyDiivbSVIZd0U5GChXELNswd9iGLGtL6QQ';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
//listLabels();
readMessages();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
/*gapi.client.gmail.users.labels.list({
'userId': 'me'
}).then(function(response) {
var labels = response.result.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});*/
}
js-api/functions.js code
function append(subject, text){
$("body").prepend("<div class='mail_box' id='mail_box" + i + "'></div>")
$("#mail_box" + i).append("<div class='message'></div>")
$("#mail_box" + i + " .message").append("<div class='subject'>" + subject + "</div>")
$("#mail_box" + i + " .message").append("<div class='text'>" + text + "</div>")
i++
}
function splitStringBySegmentLength(source, segmentLength) {
if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,segmentLength).join('')));
return target;
}
function debug1Message(msgID){
gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': msgID
}).then(function(response) {
var output = response.result;
console.warn("âš ï¸ Debug [Message: msgID:" + msgID + " ]");
console.warn(output)
});
}
function read1Message(msgID){
gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': msgID
}).then(function(response) {
var output = response.result;
for (var headerIndex = 0; headerIndex < output.payload.headers.length; headerIndex++) {
if (response.result.payload.headers[headerIndex].name == 'Subject') {
x = output.payload.headers[headerIndex].value;
var subject = x;
}
}
console.warn("âš ï¸ Debug [msgID]:" + msgID);
//var messageHTML = output.payload.parts[1].body.data
try{
var ab = output.payload.parts.length
console.warn("âš :" + ab)
for (var headerIndex = 0; headerIndex < ab; headerIndex++) {
if (response.result.payload.parts[headerIndex].mimeType == 'text/html') {
x = output.payload.parts[headerIndex].body.data;
var messageHTML = x;
}
}
}
catch(err){
try{
var messageHTML = output.payload.body.data;
}
catch(err2){
var messageHTML = "Broken/Expired message"
}
}
//var messageHTMLdecrypted = atob(messageHTML)
var result = []
/*result.push(subject)
result.push(messageHTML)*/
console.log("Subject:", subject)
//console.log("Messsage (encrypted):", messageHTML)
//console.log("Messsage (HTML):", messageHTMLdecrypted)
//document.getElementById("content").innerHTML = x
$("#content").html(subject + ";?;" + messageHTML)
y = $("#content").html().split(";?;")
z = y[1].replaceAll("-", "+")
//z = z.replaceAll("+", "+;")
//console.log(y)
if (y && y.length > 0) {
/*for (i = 0; i < y.length; i++) {
var tmp = z[i];
/*console.log(z)*/
/*var tmp_decoded = atob(z.split("+")[i]) ///FAILED
tmp_decoded = tmp_decoded.replaceAll(";", "+")
$("#content2").append(tmp_decoded)
console.warn(tmp_decoded)
}*/
//zlen = z.length / 100+1
//console.error(zlen)
//var zout = splitStringBySegmentLength(z, zlen)
//console.log(zout)
/*for (i = 0; i < zout.length; i++){
console.warn(zout[i]) //PASSED
//var tmp_decoded = atob(zout[i]) ///FAILED
//console.warn(tmp_decoded)
//$("#content2").append(tmp_decoded)
}*/
console.error(z)
try{
var tmp_decoded = atob(z);
}
catch(err){
z2 = z.split("_");
for (i = 0; i < z2.length; i++){
$("#content2").html("")
var tmp_decoded = atob(z2[i])
var old = $("#content2").html()
$("#content2").html(old + tmp_decoded)
}
}
$("#content2").append(tmp_decoded)
var decoded = $("#content2").html()
var msg = y[0]
append(msg, decoded)
$("#content2").html("")
} else {
appendPre('Message Error receive data');
}
});
}
function readMessages(){
gapi.client.gmail.users.messages.list({
'userId': 'me'
}).then(function(response) {
var output = response.result.messages;
console.log(output)
if (output && output.length > 0) {
for (i = 0; i < output.length; i++) {
var msgID = output[i].id;
read1Message(msgID)
}
} else {
appendPre('No Labels found.');
}
});
}

The mistake you have is that somewhere you have a call to
atob(window)
however, the function expects a Base64 and converts it to a number.
You will need to find out what the intention of the code was and replace the parameter passed to atob with the proper Base64 value.

Related

"jsonpointer is not defined"

I'm a university student and I'm working with JsPsych on a Jatos server. Doing an excercise I receive an error about my jspointer.
Exactly the error is:
Uncaught ReferenceError: jsonpointer is not defined at jatos.batchSession.get (jatos.js:774:13) at start:33:25
I really don't know how to solve it, cause with this kind of error I cannot retrieve my Batch Session's data to make my experiment work.
I'll show you also there my code to help you understand (it's just the specific exercise code, cause the hole set of excercises is really more vast and complex):
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title> BENVENUTO </title>
<script src="jatos.js"></script>
<script src="https://unpkg.com/jspsych#7.2.3"></script>
<script src="https://unpkg.com/#jspsych/plugin-html-keyboard-response#1.1.1"></script>
<link href="https://unpkg.com/jspsych#7.2.3/css/jspsych.css" rel="stylesheet" type="text/css" />
</head>
<body>
<style>
body {
background-color: white;
}
</style>
</body>
<script>
var jsPsych = initJsPsych ({
override_safe_mode: true,
on_finish: function(){
jatos.startComponentByPos(nextComponentPosition[componentCounter], data, JSON.stringify(data));
}
});
if (jatos.batchSession.get("level_attenzione") <= 1){
var attenzione = jsPsych.randomization.shuffle(jatos.studyInput.attenzione_1).slice(0,3)
};
if (jatos.batchSession.get("level_attenzione") == 2){
var attenzione = jsPsych.randomization.shuffle(jatos.studyInput.attenzione_2).slice(0,3)
};
if (jatos.batchSession.get("level_attenzione") > 2){
var attenzione = jsPsych.randomization.shuffle(jatos.studyInput.attenzione_3).slice(0,3)
};
if (jatos.batchSession.get("level_linguaggio") <= 1){
var linguaggio = jsPsych.randomization.shuffle(jatos.studyInput.linguaggio_1).slice(0,3)
};
if (jatos.batchSession.get("level_linguaggio") == 2){
var linguaggio = jsPsych.randomization.shuffle(jatos.studyInput.linguaggio_2).slice(0,3)
};
if (jatos.batchSession.get("level_linguaggio") > 2){
var linguaggio = jsPsych.randomization.shuffle(jatos.studyInput.linguaggio_3).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_verbale") <= 1){
var memoria_verbale = jsPsych.randomization.shuffle(jatos.studyInput.memoria_verbale_1).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_verbale") == 2){
var memoria_verbale = jsPsych.randomization.shuffle(jatos.studyInput.memoria_verbale_2).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_verbale") > 2){
var memoria_verbale = jsPsych.randomization.shuffle(jatos.studyInput.memoria_verbale_3).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_visiva") <= 1){
var memoria_visiva = jsPsych.randomization.shuffle(jatos.studyInput.memoria_visiva_1).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_visiva") == 2){
var memoria_visiva = jsPsych.randomization.shuffle(jatos.studyInput.memoria_visiva_2).slice(0,3)
};
if (jatos.batchSession.get("level_memoria_visiva") > 2){
var memoria_visiva = jsPsych.randomization.shuffle(jatos.studyInput.memoria_visiva_3).slice(0,3)
};
var componentCounter = 0;
var nextComponentPosition = attenzione.concat(linguaggio).concat(memoria_verbale).concat(memoria_visiva)
nextComponentPosition = jsPsych.randomization.shuffle(nextComponentPosition)
nextComponentPosition.splice(nextComponentPosition.length/2, 0, 2)
nextComponentPosition = nextComponentPosition.concat(3);
var data = {
level_attenzione: BatchSession["level_attenzione"],
level_linguaggio: BatchSession["level_linguaggio"],
level_memoria_verbale: BatchSession["level_memoria_verbale"],
level_memoria_visiva: BatchSession["level_memoria_visiva"],
level_gradimento: BatchSession["level_gradimento"]
};
var empty = [];
sessionStorage.setItem("nextComponentPosition", nextComponentPosition);
sessionStorage.setItem("componentCounter", componentCounter);
sessionStorage.setItem('attenzione', empty);
sessionStorage.setItem('linguaggio', empty);
sessionStorage.setItem('memoria_verbale', empty);
sessionStorage.setItem('memoria_visiva', empty);
var instructions = {
type: jsPsychHtmlKeyboardResponse,
stimulus: '<h2 style="text-align-center"> Prema il tasto INVIO per proseguire </h2>',
choices: ['Enter'],
};
var timeline = [instructions];
jsPsych.run(timeline);
</script>
</html>
I've tryed to access to the JSONfile to understand where is the error about the missing jsonpointer, but what I obtained is just:
* Getter for a field in the batch session data. Takes a name
* and returns the matching value. Works only on the first
* level of the object tree. For all other levels use
* jatos.batchSession.find. Gets the object from the
* locally stored copy of the session and does not call
* the server.
* #param {string} name - name of the field
* #return {object}
*/
jatos.batchSession.get = function (name) {
var obj = jsonpointer.get(batchSessionData, "/" + name);
return cloneJsonObj(obj);
};

JS get random value from array and update array

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

How to fix retrieving data in HTML5 after the Firebase Function finished OK?

I can't seem to find the error. In the code below, when I change the asset field, I send the values to firebase, then the function finished with status: 'ok'.
And the value event method does not read the data changes at database path
firebase.database().ref("code/" + uuid + "/result")
Could you help me please?
This is my code.
<div class='asset'></div>
<main class="app__content prop-to-show hidden" style="height: inherit;"></main>
<main class="app__content data-to-show hidden" style="height: inherit;"></main>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase.js"></script>
<script>
var config = { ... };
firebase.initializeApp(config);
</script>
<script type="module">
import PPE from "../js/ppe.min.js";
PPE.WORKER_PATH = '../js/ppe-worker.min.js';
// step 1.: Working fine
document.querySelector('.asset').addEventListener("change", coPPE);
function coPPE() {
const asset = document.querySelector('.asset').value;
const re = new PPE (asset, result => setResult(result));
};
// step 2.: Working fine
async function setResult(content) {
await setID(content);
};
// step 3.: Working fine
function setID(reid) {
var uid = firebase.auth().currentUser.uid;
var d = new Date();
var timestamp = d.getTime();
firebase.database().ref("ppe/" + uid).set({
code: reid,
timestmp: timestamp
});
};
</script>
<!--
step 4.: Working fine - cloud function set 'firebase.database().ref("code/" + id + "/result");' wnen ref('ppe/{Id}') is updated;
-->
<script type="text/javascript">
// step 5.: Nothing happens after step 4
var uuid = firebase.auth().currentUser.uid;
var statusRef = firebase.database().ref("code/" + uuid + "/result");
statusRef.on('value', function (snapshot) {
var getPropertyValue = snapshot.val();
var list = document.querySelector('.data-to-show');
var content = '';
while (list.firstChild) {
list.removeChild(list.firstChild);
}
if (getPropertyValue.rs == 0) {
content = "<div class='verified y5p' id='ok'> ... </div>";
} else if (getPropertyValue.rs == 1) {
content = "<div class='doublecheck y6p' id='twice'> ... </div>";
} else if (getPropertyValue.rs == 2) {
content = "<div class='notverified y7p' id='reject'> ... </div>";
}
document.querySelector('.data-to-show').innerHTML = content;
document.querySelector('.prop-to-show').classList.add('hidden');
document.querySelector('.data-to-show').classList.remove("hidden");
}, function (error) {
console.log("Error: " + error.code);
});
</script>

Javascript file not loading to browser

i have a problem where for some reason my .js file is not loaded to browser, when other files are. The problem is that the file that should be loaded is important for my "site" to work. Heres code:
var viewModel = new PeopleTableViewModel({
// uncaught reference error Peopetable view model is not defined
pageSize: 25,
current: data.length,
context: document.getElementById('table')
});
var comparator = new Comparators();
function init() {
viewModel.next();
}
Heres my HTML :
<div id="table"></div>
<button onclick="viewModel.prev()">PREV</button>
<button onclick="viewModel.next()">NEXT</button>
<script type="application/javascript" src="scripts/DATA.js"></script>
<script type="application/javascript" src="scripts/Comparators.js"></script>
<script type="application/javascript" scr="scripts/PeopleTableViewModel.js"></script>
<script type="application/javascript" src="scripts/ListOfPeople.js"></script>
<script type="application/javascript" src="scripts/scripts.js"></script>
<script type="application/javascript" src="scripts/Person.js"></script>
</body>
And PeopleTableViewModel.js:
function PeopleTableViewModel(config) {
var self = this;
self.people = new ListOfPeople();
self.currentPage = 0;
self.pageSize = config.pageSize;
self.context = config.context;
self.next = function() {
//alert('kliknąłeś następny');
self.people.clear();
var begin = (self.currentPage) * self.pageSize;
var end = (self.currentPage + 1) * self.pageSize;
getData(begin, end);
self.currentPage++;
self.context.innerHTML = self.people.toTable();
}
self.prev = function() {
//alert('kliknąłeś poprzedi');
self.people.clear();
if (self.currentPage - 1 >= 0) {
self.currentPage--;
}
var begin = (self.currentPage) * self.pageSize;
var end = (self.currentPage + 1) * self.pageSize;
getData(begin, end);
self.context.innerHTML = self.people.toTable();
}
self.sort = function(comparer) {
data.sort(comparer);
self.currentPage = 0;
self.next();
}
var getData = function(begin, end) {
if (end > data.length) {
end = data.length;
}
if (begin < 0) {
begin = 0;
}
for (var i = begin; i < end; i += 1) {
self.people.addPerson(data[i]);
}
}
}
Thank you for taking time on my issue !
You made a mistake in the html markup.
<script type="application/javascript" scr="scripts/PeopleTableViewModel.js"></script>
instead of
<script type="application/javascript" src="scripts/PeopleTableViewModel.js"></script>

JavaScript and HTML Form 'Bank'

I want to be able to have a form that takes a 'deposit' or 'withdraw' and will add or subtract for a variable. Then, I would like to be able to put that variable in the webpage, and be able to keep it for a day or two. I do not know what is wrong with my code at this point.
<html>
<head>
<script language="JavaScript">
<!-- hide this script from old browsers
//Bank
var bank = 0;
var bank_name = "The Bank of Pacycephalosaurus";
var bank_interestPolicy = 0;
var bank_interestPolicy_interestAmount = 2;
var bank_ineterestPolicy_interest = function (amount) {
var interestGain = bank_contents_money / bank_interestPolicy_interestAmount;
var bank_contents_money = bank_contents_money + interestGain;
};
var bank_contents = 0;
var bank_contents_money = 0;
var bank_contents_items = "None";
var bank_withdrawAmount = "0";
var bank_depositAmount = "0";
var bank_withdraw = function (amount) {
//Check if there is money
if (bank_contents_money < amount) {
alert("Withdraw DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + wallet_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
form.bank_money.value = bank_contents_money - amount;
wallet_money = wallet_money + amount;
}
}
};
var bank_deposit = function (amount) {
//Check if there is money
if (wallet_money < amount) {
alert("Deposit DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + bank_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
alert("The Amount: " + amount);
form.bank_money.value = bank.contents_money + amount;
bank_contents_money = bank.contents_money + amount;
alert("The Amount: " + amount);
bank_opening(amount);
}
}
};
var bank_opening = function (money) {
alert("You have $" + bank_contents_money + " in your bank.");
$.cookie("bankMoney", money, {
expires: 1
});
alert($.cookie("example"));
};
var wallet = 0;
var wallet_name = "Wallet of You!";
var wallet_money = 0;
bank_opening();
// done hiding from old browsers -->
</script>
</head>
<body>
<form>
<h2>Bamk</h2>
Enter a number to withdraw or deposit:
<INPUT NAME="deposit" VALUE="0" MAXLENGTH="15" SIZE=15>
<p>
<INPUT NAME="depos" VALUE="Deposit" TYPE=BUTTON
onClick=bank_deposit(deposit.form)>
<p>
<p>
<INPUT NAME="withd" VALUE="Withdraw" TYPE=BUTTON
onClick=bank_withdraw(this.form)>
<p>
The amount in a bank is:
<INPUT NAME="bank_contents_money" READONLY SIZE=15>
</form>
</body>
</html>

Categories

Resources