Javascript Firebase-Storage image upload not working - javascript

I am trying to upload an image from HTML form to firebase storage using an external JS file, but when I try to upload the image file (which is not empty - it exists) the path to the image location is not created on firebase storage when I execute the storageRef.put(image); function, and also the image itself (obviously) not being saved.
this is my code:
index.html file:
<!DOCTYPE html>
<html>
<head>
<title>אורט ביאליק עדכון פרטים</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<style>
html, body {
min-height: 100%;
direction: rtl
}
body, div, form, input, select, p {
padding: 0;
margin: 0;
outline: none;
font-family: Roboto, Arial, sans-serif;
font-size: 16px;
color: #eee;
}
body { background: url("https://firebasestorage.googleapis.com/v0/b/XXXXXXXX.appspot.com/o/not%20to%20delete%2Fbackground.jpeg?alt=media&token=b5e0cc70-dc1c-40c7-a3fa-15694541828e") no-repeat center; background-size: cover; }
h1, h2 {
text-transform: uppercase;
font-weight: 400;
}
h2 {
margin: 0 0 0 8px;
}
.main-block {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
padding: 25px;
background: rgba(0, 0, 0, 0.5);
}
.left-part, form {
padding: 25px;
}
.left-part {
text-align: center;
}
.fa-graduation-cap {
font-size: 72px;
}
form {
background: rgba(0, 0, 0, 0.7);
}
.title {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.info {
display: flex;
flex-direction: column;
}
input, select {
padding: 5px;
margin-bottom: 30px;
background: transparent;
border: none;
border-bottom: 1px solid #eee;
}
input::placeholder {
color: #eee;
}
option:focus {
border: none;
}
option {
background: black;
border: none;
}
.btn-item, button {
padding: 10px 5px;
margin-top: 20px;
border-radius: 5px;
border: none;
background: #26a9e0;
text-decoration: none;
font-size: 15px;
font-weight: 400;
color: #fff;
}
.btn-item {
display: inline-block;
margin: 20px 5px 0;
}
button {
width: 100%;
}
button:hover, .btn-item:hover {
background: #85d6de;
}
#media (min-width: 568px) {
html, body {
height: 100%;
}
.main-block {
flex-direction: row;
height: calc(100% - 50px);
}
.left-part, form {
flex: 1;
height: auto;
}
}
</style>
</head>
<body>
<div class="main-block">
<div class="left-part">
<img src="https://firebasestorage.googleapis.com/v0/b/XXXXXXXXX.appspot.com/o/not%20to%20delete%2Fkiryat_bialik_img.jpg?alt=media&token=5d637243-1cb1-430c-a7c5-1a98329bb3a0">
</div>
<form name="RegForm" action="/">
<div class="title">
<i class="fas fa-pencil-alt"></i>
<h2>מכללת אורט ביאליק - עדכון פרטים אישיים</h2>
</div>
<div class="info">
<input class="fname" type="text" name="HEfname" id="HEfname" maxlength="20" required autofocus placeholder="שם פרטי">
<input class="fname" type="text" name="HElname" id="HElname" maxlength="20" required placeholder="שם משפחה">
<input class="fname" type="text" name="ENfname" id="ENfname" maxlength="20" required placeholder="שם פרטי באנגלית">
<input class="fname" type="text" name="ENlname" id="ENlname" maxlength="20" required placeholder="שם משפחה באנגלית">
<input type="text" name="Email" inputmode="email" id="email" required maxlength="40" placeholder="Email">
<input type="text" name="id" id="id" required maxlength="9" placeholder="מספר תעודת זהות">
<input type="file" name="img" id="img" required accept="image/*">
</div>
<button type="submit" name="submit" id="submit" value="submit" onclick="return validation();" href="/">שלח</button>
</form>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-storage.js"></script>
<script src="js/formValidation.js"></script>
<script src="js/formSubmission.js"></script>
</body>
</html>
formSubmission.js:
// My web app's Firebase configuration
var firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX",
appId: "XXXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Reference Users collection
var databaseRef = firebase.database().ref('Users');
// Listen for form submit
document.forms.RegForm.addEventListener('submit', submitForm);
// Submit form
function submitForm() {
//if (validation()) {
// Get values
var HEfname = getInputVal('HEfname');
var ENfname = getInputVal('ENfname');
var HElname = getInputVal('HElname');
var ENlname = getInputVal('ENlname');
var email = getInputVal('email');
var id1 = getInputVal('id');
var imageFile = document.getElementById('img').files[0];
//this VAR's are used in 'saveUser()'; function. ---NOT IN USE---
// unused value=5; if false value=0; if true value=1
var isSavedDatabase = false; // if user data successfully commited to Firebase Database.
var isSavedImage = false; // if user image successfully commited to Firebase Storage.
// Save User
saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile);
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save User to firebase
function saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile) {
// reference to image path in storage 'passportImages/id1' (id1 is current user ID)
var imageRef = firebase.storage().ref().child('passportImages/' + id1);
//save User to database
var newUserRef = databaseRef.child(id1);
newUserRef.set({
HEfname: HEfname,
HElname: HElname,
ENfname: ENfname,
ENlname: ENlname,
email: email,
id: id1
}, function (error) {
if (error) {
// The write failed
console.log("User info could not be saved: " + error);
} else {
// Data saved successfully!
isSavedDatabase = true;
console.log("User info saved successfully!");
saveImage(imageFile, id1);
//imageRef.delete(); // remove user image from storage if his info could not be saved t database.
}
});
//save image to storage by ID
function saveImage(imageFile, id) {
// Upload file to the object 'passportImages/id1' (id1 is current user ID)
var uploadTask = firebase.storage().ref().child('passportImages/' + id).put(imageFile);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function (snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function (error) {
databaseRef.child(id).remove(); //remove user info from database if his image could not be uploaded to storage too.
console.log(error);
window.alert("Something went wrong, please try again");
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
console.log("Image: User doesn't have permission to access the object");
break;
case 'storage/canceled':
// User canceled the upload
console.log("Image: User canceled the upload");
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
console.log("Image: Unknown error occurred, inspect error.serverResponse");
break;
}
}, function () {
// Upload completed successfully!
isSavedImage = true;
console.log("Image uploaded successfully!");
finalCall();
});
//if all data commited successfully to Firebase pop a massage and reset form.
function finalCall() {
// Show alert
window.alert("Your info has been sent!");
// Clear form
document.forms.RegForm.reset();
}
}
//}
}

It is probably because you assign the submit type to your button. Your form is probably submitted before the submitForm() method is triggered.
If this assumption is correct, changing the type to button, as follows, should do the trick:
<button type="button" id="submit" onclick="return validation();" href="/">שלח</button>
See the W3 specification for more detail.

Related

How to save web application input data in the same web location?

I would like to save input data from web application in the same web location where the .html file placed. The saved file should be over ride with the new data every time we click the button. Currently, code downloads file to local. How to place the file in the web location and it should be over ride with new data?
Code:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button]{
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<!--Add few elements to the form-->
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</div>
</body>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
// This variable stores all the data.
let data =
'\r Name: ' + name.value + ' \r\n '
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.txt'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
</script>
</html>
Javascript doesn't allow save or read files locally without user's consent (aka download/upload). If you need store data for your website/application, you can use WebStorage instead.

How can I let an html page rendered by node.js call back to the node.js file? [duplicate]

This question already has answers here:
Link index.html client.js and server.js
(1 answer)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
I am trying to create a registry system with node.js and HTML, the problem is that my html page is rendered by node.js, and when i want to call it back to the node.js file, it seems like it cannot find the js file.
Here is my js code:
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type': 'text/html' });
const html = fs.readFileSync('Index.html');
res.end(html);
}).listen(3000, () => {
console.log('running on 3000');
});
function insertdatabase() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
const { Connection, Request } = require("tedious");
// Create connection to database
const config = {
authentication: {
options: {
userName: "******", // update me
password: "**********" // update me
},
type: "default"
},
server: "*********************", // update me
options: {
database: "************", //update me
encrypt: true
}
};
const connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
queryDatabase();
}
});
function queryDatabase() {
console.log("Reading rows from the Table...");
// Read all rows from table
const request = new Request(
`INSERT INTO [dbo].[dbo] (email, username, password)
VALUES ('${email}', '${username}', '${password}');
SELECT * FROM [dbo].[dbo] `,
(err, rowCount) => {
if (err) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
}
);
request.on("row", columns => {
columns.forEach(column => {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
}
and here is my html code:
<html>
<head lang="en">
<meta charset="UTF-8">
<style>
body {
margin: 0;
padding: 0;
background: url() no-repeat;
background-size: cover;
font-family: sans-serif;
background-image: url(image/hbg.gif)
}
.topnav {
overflow: hidden;
background-color: whitesmoke;
}
.topnav a {
float: left;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: white;
color: black;
}
.topnav a.active {
background-color: black;
color: white;
}
.register-box {
width: 380px;
height: 480px;
position: relative;
margin: 6% auto;
background-color: whitesmoke;
padding: 5px;
}
.userinput-box {
width: 100%;
padding: 10px 0;
margin: 5px 0;
border-left: 0;
border-top: 0;
border-right: 0;
border-bottom: 1px;
outline: none;
background: transparent;
}
.userinput-group {
top: 180px;
position: absolute;
width: 280px;
}
.button {
background-color: #cbcbcb;
}
</style>
<script src="server.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="../Subpages/account.html">Log in</a>
Home
News
Contact
About
Shopping Cart
Billing info
</div>
<div class="register-box">
<br /><br /><center><h1><b>Register Account</b></h1></center>
<form class="userinput-box">
<center>
<h3>Email: <input type="text" name="email" id="email" required></h3>
<br /><h3>Username: <input type="text" name="username" id="username" required></h3>
<br /><h3>Password: <input type="password" name="password" id="password" required></h3>
</center>
</form>
<center>
<input type="submit" class="button" onclick="insertdatabase()">
<br />
</center>
</div>
</body>
</html>
My guess is that maybe an html page rendered by js cannot find other files? This guess is based on when I add the css file to the project, it cannot be found either. Is there a way to fix this problem, or do I have to try another method?
Here is an example of what you're trying to do, but putting the function in a client-sided file and using id to listen on the buttons. You should really avoid just putting an import to the server-side script in a client-sided file as it will be public and that could cause huge security issues.
If you want to use functions that are in your server.js file, you can use this. It's a way to use form submission in your express application.
In addition, don't put your submit button outside your form.

Enter the prototype of an Object.prototype.function(), where all the EventListeners are safed (Javascript)

I am working on an assignment, that constructs a small library. The project requires, that the user can input the title of a book, its author, number of pages and if the user has already read it. Then the content gets displayed on the page.
Here's the code (work in progress):
let myLibrary = [];
let submitBtn = document.querySelector("#submitBtn");
let textInput = document.querySelectorAll("input");
let addNew = document.getElementById("addNew");
let fieldSet = document.getElementById("fieldset");
let cancelBtn = document.querySelector("#cancelBtn");
let bookDisplay = document.getElementById("bookDisplay");
let flexItems = document.getElementsByClassName("flexItems");
// object Constructor for new books
class Book {
constructor(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
}
Book.prototype.addToDisplay = function() {
let newDiv = document.createElement("div");
bookDisplay.appendChild(newDiv).className = "flexItems";
let newSpan = document.createElement("span");
flexItems[myLibrary.length-1].appendChild(newSpan).className = "spanItem";
newSpan.innerText = this.title;
this.read === true ? flexItems[myLibrary.length-1].style.backgroundColor = "green" :
flexItems[myLibrary.length-1].style.backgroundColor = "red";
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = this.author + "\n" + this.title + "\n" + this.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = this.title;
})
}
// creates a new instance of Book and pushes the object into the array
let addToLibrary = function addToLibrary() {
newBook = new Book(textInput[0].value, textInput[1].value, textInput[2].value, textInput[3].checked)
myLibrary.push(newBook);
newBook.addToDisplay();
};
// eventlistener, to submit a new Book to the library
submitBtn.addEventListener("click", addToLibrary);
// sets the form's display from block to non-visible
let cancel = function cancel() {
fieldSet.style.display = "none";
}
// cancels the form and returns back
cancelBtn.addEventListener("click", cancel);
// sets the form's display from non-visible to visible
let openForm = function openForm() {
fieldSet.style.display = "block";
}
// opens form to add new book
addNew.addEventListener("click", openForm);
body {
margin-left: 20px;
}
h1 {
text-align: center;
}
#fieldset {
position: fixed;
z-index: 2;
border: none;
display: none;
background: #3CBC8D;
border-radius: 10px;
right: 1%;
top: 2%;
width: 400px;
height: auto;
overflow: auto;
}
button {
cursor: pointer;
}
.display {
display: flex;
flex-direction: row;
flex-wrap: wrap;
position: relative;
}
.flexItems {
position: relative;
display: flex;
margin: 5px;
color: black;
font: Georgia;
font-size: 20px;
height: 200px;
width: 200px;
align-items: center;
border: 2px solid gray;
transition: 500ms;
border-radius: 5px;
}
.spanItem {
width: 100%;
text-align: center;
white-space: wrap;
overflow: hidden;
text-overflow: ellipsis;
}
.display .flexItems:focus,
.display .flexItems:hover {
transform: scale(1.2);
z-index: 1;
}
#addNew {
position: fixed;
z-index: 2;
border: none;
background: #3CBC8D;
color: white;
border-radius: 10px;
right: 2%;
top: 2%;
width: 100px;
height: 50px;
overflow: auto;
cursor: pointer;
}
/*. Could be additionally used for the hover-effect, but doesnt look that nice for more than one row
flexItems:hover ~.flexItems {
transform: translateX(25%);
}
.display:focus-within .flexItems,
.display:hover .flexItems {
transform: translateX(-25%);
}
.flexItems:focus ~.flexItems,
.flexItems:hover ~.flexItems {
transform: translateX(25%);
} */
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Library</title>
</head>
<body>
<div><h1>My book library</h1></div>
<div id="bookDisplay" class="display">
</div>
<div>
<button id="addNew">Test</button>
</div>
<fieldset id="fieldset">
<form id="form">
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title" class="usrInput">
</div>
<div>
<label for="author">Author: </label>
<input type="text" name="author" id="author" class="usrInput">
</div>
<div>
<label for="number">Number of pages: </label>
<input type="number" name="number" id="number" class="usrInput">
</div>
<div>
<label for="read">Already read?: </label><br>
Y <input type="radio" name="read" id="read" value="Y" class="read">
N <input type="radio" name="read" id="read" value="N" class="read">
</div>
<button id="submitBtn" type="button">Submit</button>
<button id="cancelBtn" type="button">Cancel</button>
</fieldset>
</div>
</body>
</html>
**My question: ** The code is working until here. But I have my concerns with the mouseenter-Eventlistener. On mouseenter, I want to add a <button>, to edit the book's value. And maybe there is moreto be added in the future. That would mean the àddToDisplay() function eventually will get clunky. So I was wondering, if I could enter the Object.prototype of the addToDisplay() function and store all eventListeners in its prototype. Is this possible in Javascript?
The only way I could solve it right now is, to write an extra function for the eventlisteners. But it seems, that this way, I'm just going back to normal function expressions with dozens of values to pass by:
Book.prototype.addToDisplay = function() {
// (...)
mousehover(this, newDiv, newSpan)
}
let mousehover = function mousehover(test, newDiv, newSpan) {
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = test.author + "\n" + test.title + "\n" + test.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = test.title;
})
}
Hope I got the problem across. It's the first assignment to Objects I'm working on.
Thanks for any answers and links to informative sources.

using local storage with javascript

I have a signup form that saves user data. The data doesn't save to local storage when it is supposed to. The app is supposed to sign up a user and save the data to the local storage, if someone attempts to sign up with already existing username, the app prevents the user from doing that.
the javascript file does the following
1) prevents users from signing up with already existing username
2) saves an object to the local storage which is passed into an array
var signUpBtn = document.querySelector('#signUp');
var signUpOver = document.querySelector('.signup__overlay');
var signInBtn = document.querySelector('#signIn');
var signInOver = document.querySelector('.signin__overlay');
var fullname = document.querySelector('#name');
var email = document.querySelector('#email');
var password = document.querySelector('#password');
var age = document.querySelector('#age');
var occupation = document.querySelector('#occupation');
var Address = document.querySelector('#address');
var signupSubmitClicked = document.querySelector('#signupClicked');
signupSubmitClicked.addEventListener('click', () => {
if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
alert("incomplete datails, please fill up everything")
} else {
alert("item created")
addUser(fullname, email, password, age, occupation, Address);
}
});
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
var saveUser = (users) => {
localStorage.setItem('userData', JSON.stringify(users));
};
var addUser = (fullname, email, password, age, occupation, Address) => {
var users = fetchUsers();
var user = {
fullname,
email,
password,
age,
occupation,
Address
};
var duplicateUsers = users.filter(user => user.email === email);
if (duplicateUsers.length === 0) {
users.push(user);
saveUser(users);
return user;
}
};
/*************
signup popup
*************/
signUpBtn.addEventListener('click', () => {
signUpOver.style.display = 'block';
});
signUpOver.addEventListener('click', () => {
if(event.target == signUpOver){
signUpOver.style.display = "none";
}
});
/*************
signup popup
*************/
/*************
signin popup
*************/
signInBtn.addEventListener('click', () => {
signInOver.style.display = 'block';
});
signInOver.addEventListener('click', () => {
if(event.target == signInOver){
signInOver.style.display = "none";
}
});
/*************
signin popup
*************/
/** the end */
body {
width: 100%;
margin: 0;
background-color: #F8F9F9;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#mainPage,
#userPage {
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#userPage {
display: none;
}
/********************
overlay
********************/
.signup__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signup__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
.signin__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signin__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
/********************
overlay ending
********************/
.headerMain {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.headerUser {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.upButton {
margin-bottom: 20px;
}
.upButton, .inButton {
padding-top: 15px;
padding-bottom: 15px;
cursor: pointer;
width: 100%;
max-width: 200px;
background-color: #239B56;
border: #239B56;
color: snow;
}
label {
padding-top: 20px;
}
label,
input {
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>User system</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="mainPage">
<div class="signup__overlay">
<div class="signup__content">
<form>
<label for="name">Full Name</label>
<input required type="text" id="name" name="name">
<label for="email">Email</label>
<input required type="text" id="email" name="email">
<label for="password">Password</label>
<input required type="password" id="password" name="password">
<label for="age">Age</label>
<input required type="text" id="age" name="age">
<label for="occupation">Occupation</label>
<input required type="text" id="occupation" name="occupation">
<label for="address">Address</label>
<input required type="text" id="address" name="address">
<input type="submit" id="signupClicked">
</form>
</div>
</div>
<div class="signin__overlay">
<div class="signin__content">
<form>
<label for="email">Email</label>
<input required type="text" id="Email" name="email">
<label for="email">Password</label>
<input required type="Password" id="Password" name="Password">
<input type="submit" id="signinClicked">
</form>
</div>
</div>
<header class="headerMain">User System</header>
<section>
<button class="upButton" id="signUp">Sign Up</button>
<button class="inButton" id="signIn">Sign In</button>
</section>
</div>
<div id="userPage">
<header class="headerUser">User System</header>
<section>
</section>
</div>
<script src="js/index.js"></script>
</body>
</html>
Okay so here are several things we need to discuss about. Let's start with the code:
When you have a <input type="submit"> inside a form, the button will re-fresh the page when it's clicked. It's the behaviour by default of the submit button. That's why nothing is stored on the localStorage. To prevent this from happening, you need to use the event.preventDefault() method. Check out this link.
After fixing the preventDefault bug, we face another problem: the function fetchUsers returns null. That's because localStorage.getItem('userData') returns a null if nothing is on the localStorage. The try/catch dosn't work here, since localStorage.getItem('userData') dosn't throw an error. If nothing is there, it simply returns a null (but no error). Solucion: change your return to use a ternary operator:
return JSON.parse(userString) ? JSON.parse(userString) : [];
Using document.querySelector('#name') dosn't return what the user has written on that input. To get what the user writes on an input, you have to use: document.querySelector('#name').value
If you put the var fullname = document.querySelector('#name').value; on the global scope (at the begining of the script) it will take the value that the input had when the script was first loaded (which is... ""). You want to take that value every time the user clicks on the button. So you have to move those variables (fullname, email, password) inside the signupSubmitClicked.addEventListener.
And now the most important thing to discuss: why are you trying to store personal data on the localStorage? You need to be aware that the information on the localStorage is not secure, not really stored into any server, and not recommended at all. If you are doing this project to practice and learn it's okay. You can use this as a playground to learn. But remember: if you want to store personal information in a real-world way, you need to create a server (a back-end to your web).
Hi Opeyemi and welcome on StackOverflow.
First of all you have to know that this way of doing is good for testing, but it won't fit for any production applications.
The reason this is failing is because this function :
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
is actually returning a null value. Due to that null value, the rest of the code get stuck.
This part of the code will get stuck for example :
var duplicateUsers = users.filter(user => user.email === email);
Normally these errors appear in your console, so you really should check that out.
Once that is fixed it should be pretty easy to fix the rest

get file object from called window javascript

I am trying to open a window and process the file in the calling JavaScript. I can pass the file name using localStorage but if I return the file I can't get it right.
I can't use this solution due to restrictions of the system I am calling the JavaScript from:
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.click();
Can a file object be passed using localStorage or should I use another method?
My code is:
<!DOCTYPE html>
<html>
<script language="JavaScript">
function testInjectScript2(){
try {
var myhtmltext =
'<input type="file" id="uploadInput3" name=\"files[]" onchange=\'localStorage.setItem("myfile",document.getElementById("uploadInput3").files[0]);\' multiple />';
console.log("myhtmltext="+myhtmltext);
var newWin2 = window.open('',"_blank", "location=200,status=1,scrollbars=1, width=500,height=200");
newWin2.document.body.innerHTML = myhtmltext;
newWin2.addEventListener("unload", function (e) {
if(localStorage.getItem("myfile")) {
var f = localStorage.getItem("myfile");
alert ('in function.f='+f);
alert ('in function.f.name='+(f).name);
localStorage.removeItem("myfile");
}
});
} catch (err) {
alert(err);
}
}
</script>
<body>
<input type="button" text="testInjectScript2" onclick="testInjectScript2()" value="testInjectScript2" />
</body>
</html>
First of all, welcome to SO. If I get you right, you want to upload a file using a new window and get that file using localStorage onto your main page. This is a possible solution. However, please do also note that the maximum size of the localStorage can vary depending on the user-agent (more information here). Therefore it is not recommend to use this method. If you really want to do this, please have a look at the first snippet.
var read = document.getElementById("read-value"), open_win = document.getElementById("open-win"), win, p = document.getElementById("file-set");
open_win.addEventListener("click", function(){
win = window.open("", "", "width=200,height=100");
win.document.write(
'<input id="file-input" type="file"/>' +
'<script>' +
'var input = document.getElementById("file-input");' +
'input.addEventListener("change", function(){window.localStorage.setItem("file", input.files[0]);})'+
'<\/script>'
);
})
read.addEventListener("click", function(){
var file = window.localStorage.getItem("file");
if(file){
p.innerText = "file is set";
}else{
p.innerText = "file is not set";
}
})
<button id="open-win">Open window</button>
<br><br>
<!-- Check if file is set in localStorage -->
<button id="read-value">Check</button>
<p id="file-set" style="margin: 10px 0; font-family: monospace"></p>
<i style="display: block; margin-top: 20px">Note: This only works locally as SO snippets lack the 'allow same origin' flag. i.e. just copy the html and js into a local file to use it.</i>
However, why not use a more elegant solution:
Simply using a modal. When the input value changes you can simply close the modal and get the file value without all the hassle of a localStorage.
// Get the modal, open button and close button
var modal = document.getElementById('modal'),
btn = document.getElementById("open-modal"),
span = document.getElementById("close"),
input = document.getElementById("file-input"),
label = document.getElementById("input-label"), file;
// When the user clicks the button, open the modal
btn.addEventListener("click", function() {
modal.style.display = "block";
})
// When the user clicks on <span> (x), close the modal
span.addEventListener("click", function() {
modal.style.display = "none";
})
input.addEventListener("change", function(){
file = input.files[0];
modal.style.display = "none";
//Change value of the label for nice styling ;)
label.innerHTML = input.files[0].name;
//do something with your value
})
// When the user clicks anywhere outside of the modal, close it
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
})
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 10px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal h2 {
font-family: sans-serif;
font-weight: normal;
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* Input styles, added bonus */
.file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.file-input + label {
font-size: 1.25em;
font-weight: 700;
padding: 10px 20px;
border: 1px solid #888;
display: inline-block;
cursor: pointer;
font-family: sans-serif;
}
.file-input:focus + label,
.file-input + label:hover {
background-color: #f7f7f7;
}
<!-- Trigger/Open The Modal -->
<button id="open-modal">Open Modal</button>
<!-- The Modal -->
<div id="modal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close" class="close">×</span>
<h2><i>Upload a file?</i></h3>
<input id="file-input" name="file-input" class="file-input" type="file"/>
<label id="input-label" for="file-input">Upload a file</label>
</div>
</div>
Hope it helps! Let me know!
Cheers!

Categories

Resources