Rigth now i'm creating my own website and there need to be a log in function. I've made a sign up page that retrieves data from the input fields and now comes the problem. I don't know how to save the passwords and username etc. Is it possible to save this into a text file and every time i open the website it retrieves this data? So, yes how do i do this and if this can't is there another way?
Here you see the code it retrieves. These variables need to be safed in a text file and retrieved next time website will be opend
var voornaam = document.getElementById("voorn").value;
var achternaam = document.getElementById("achtern").value;
var mail = document.getElementById("mail").value;
var password = document.getElementById("pass").value;
var gender = document.getElementById("iGender").value;
Solution:
Use a Database to save this information. Here a some Databases Mongo DB and Firebase
https://www.firebase.com/
Here's a course for Firebase http://www.codecademy.com/en/tracks/firebase
In addition to hashing the password, you probably want to be storing this information in a database. You will then have to add some logic to your application so that when a user logs in to your website, the values they enter into the log in form are checked against the values stored in the database when they signed up. In very general terms, that is probably the most standard architecture to get a log in functionality up and running.
You will have to write a service on your server that takes the form values, checks them against a database and then updates the HTML accordingly.
You could create a cookie and read it when the page loads: http://www.w3schools.com/js/js_cookies.asp
Create: document.cookie = "voornaam="+voornaam
Read: $(function(){ voornaam = document.cookie.replace("voornaam=",""); })
EDIT:
To save objects, you can use the JSON-library like so:
document.cookie = JSON.stringify({foo:"bar"}); cookieObject = JSON.parse(document.cookie);
But have in mind that the user can read and manipulate this cookie...
Related
var userInfo = [];
var myCostum;
//documentgetElementById("registerForm");
document.getElementById("registerForm").addEventListener("click", function ()
{
//var register = document.querySelector('#registerForm');
var name = document.querySelector('#fN').value;
var lastN = document.querySelector('#lN').value;
var userName = document.querySelector('#uN').value;
var passwrd = document.querySelector('#pS').value;
userInfo.push([name,lastN,userName,passwrd]);
localStorage.setItem("myCostum", JSON.stringify(userInfo));
});
I am using separate files for j, my website has a navigation bar with home,register,login,about me and shopping car. this code works fine if i register more than one user, i can see the users in the local storage on all pages and i can even sign in. the problem is when i go to register again and register a new user the users that i reister before are deleted and replaced by the new user. also if i go to home page i can an error (Uncaught TypeError: Cannot read property 'addEventListener' of null
at even-listener.js:9). i just do not had idea why register page seems to work but the rest not. I had another code using onclick in html but the same it does not give any error in any page but the users gone when i register new one after navigating through my pages. this is the first time using localStorage and i do not can i do or if it is normal. i am stack and i need to keep adding more code but i want to solve this problem first.
Lots of things going on here, but let me start from the basics.
1st never use local storage for sensitive information such as usernames and passwords. There's a lot of sites that copy local storages and send it to malicious people.
2nd you could in theory use session storage limited to the tab, but you still could be under the danger of xss.
3rd when the browser closes, all your data will be lost from the local storage anyway
As for your code. Your user info, should not be initiated as empty. You must get the previous value from local storage and push to it. Otherwise you are just overriding the previous value.
var userInfo = JSON.parse(localStorage.getItem('myCustom'));
What is the best practice to create unique shareable urls for some text lists users create?
It's a single page website with a content div where users create text lists. Once they click share, how can I store those values inside a shareable url so that another user going to that address loads the same list?
I'm using html, js, jquery, php.
EDIT: as suggested below i'm already saving the lists on a database (firebase), and each have an unique ID, so I'd need to understand how I can create urls with a list id in it, and how to read the url back.
EDIT 2: so this is the code i'm using right now, combining answers from marzelin and the Alchemist Shahed in my other question about my database structure (Firebase how to find child knowing its id but not its parent's id (js)):
//js inside window load function:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('users');
// var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
// console.log(keyOfDynamicHtmlItemRef);
// dynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
// texta.innerHTML = dynamicHtmlSnap.val();
// });
dynamicHtmlListRef.once('value').then((snapshot)=>{
snapshot.forEach(function(data) {
if (data.key == keyOfDynamicHtmlItemRef) {
myVar = data.c;
myContentDiv.innerHTML = myVar;
}
});
});
}
and i'm simply trying to manually write the url in the searchbar as a first step, as https://example.com/?share=<random list id i copied from db>, but it does nothing.
So the way I would to this is I would have the users share click trigger a save to database saving all the dynamically generated content into a table.
One of the table values would be a randomly generated unique identifier of some sort that I would use as a query in the url like https://www.example.org/?share=skd822475
Then when a user visits the site and that query is in the url id use the unique identifier to look up the database and publish the dynamic content back on the page.
I would also put a half life on the database entry's of say no more than 30 days so that it doesn't clog up the db.
Saving data and creating shareable link:
document.querySelector(".share").addEventListener("click" => {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.push();
dynamicHtmlItemRef.set(userCreatedDynamicHtml);
var keyOfDynamicHtmlItem = dynamicHtmlItemRef.key;
var linkToDynamicHtmlItem = `${window.location}?share=${keyofDynamicHtmlItem}`;
alert(`link: ${linkToDynamicHtmlItem}`)
})
Showing the dynamic HTML based on query parameters:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
keyOfDynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
document.querySelector(".dynamic-html-mountpoint").innerHTML = dynamicHtmlSnap.val();
});
}
Let's start with the first question "How to create urls with a list id in it?"
The thing is that to answer this one we need to answer the second question first witch is
"How to read the url back?"
Consider that you have a php page named "draft". when a user visit https://www.example.com/draft?listId=an_id you will get listId using php like so $_GET("listId") and use that value to retrieve the list data and display the page content.
Now coming back to the first question, if the user share the draft like in social media (ex: facebook) then there is no problem because he will share a link and all his followers and any other user can access it easily. but if the user just save the draft then you will have to change the page url dynamically like this window.history.pushState(null, null, '/draft?listId=your_newly_created_id'); and so the user will copy the url and do whatever he wnt with it (sharing it in stackoverflow maybe example using jsfiddle http://jsfiddle.net/F2es9/ (you can change the url to look like this using 'htaccess' file)) at the end I would like to tell you that we don't "create" urls.
Edit
without using php code (or any other server side code). the difference will be in retrieving the data.
instead of using $_GET("listId") you will use new URL(window.location).searchParams.get("listId") to get the list id in javascript then using this value you can retrieve data from firebase and display your content
I have created a form where a user gets to type in data that is saved in variables when the data is submitted. I am requesting a solution that will both save the user's data whilst also redirecting the user to a new .html-page when the button is pressed.
<button type="button" onclick="getInfo()">Submit</button>
As you can see above, the button is activating a function, that will save the info like this:
function getInfo(){
var firstname = document.getElementById("firstname").value
var lastname = document.getElementById("lastname").value
var adress = document.getElementById("adress").value
var password1 = document.getElementById("password1").value
var password2 = document.getElementById("password2").value
}
How can I make this possible? Sincerely, Decentralized.
Hi You can use form action with multiform attribute just like this
<form id="form_name" action="yourhtmlname.html" method="post" class="pure-form" enctype="multipart/form-data">
Maybe you are searching for something like that :
function getInfo(){
var firstname = document.getElementById("firstname").value
var lastname = document.getElementById("lastname").value
var adress = document.getElementById("adress").value
var password1 = document.getElementById("password1").value
var password2 = document.getElementById("password2").value
localStorage['firstname'] = firstname; // store data into browser's storage
window.location = 'http://overpage.html'; // change the browser's page
}
Note :
you can access data one the ther page using
var firstnameNewPage = localStorage['firstname'];
take a look at sessionStorage if you want to keep data available only for session usage
First of all, this is not how you should handle credentias and authentication, but for the sake of this question, I'll ignore that.
Since your question is very broad and can have many possible answers.
So my answer is going to be general
Here are some of the ways you can store this data and display it in another page are:
Send the data to a server, so it can be stored in the server's session or database to be retrieved latter (via an ajax call, or html forms).
Make your app a single page application so all your 'pages' share a state that can be used to move data around.
Some examples of javascript frameworks from Wikipedia that are implemented as SPA:
AngularJS, Ember.js, Meteor.js, ExtJS and React
Use a browser APIs called sessionStorage or localStorage.
They can be used to store key-value pairs of strings to be accessed latter for.
You could also store JSON data in them using the JSON.parse and JSON.stringify functions.
My suggestion:
From these possibilities I would say option 3 (localStorage) would be the easiest to implement with something like:
localStorage.setItem('first name', fname);
and
var fname = localStorage.getItem('first name');
Which would save these values in the browser.
And you can do location.replace('/path/to/other/page.html') right after that and load these values in the other page as long as you use it in the same domain.
I have an intranet site with multiple page links linking to other pages within the site on each page. The issue is that if I login to my profile for example I have no problem, but if I click on a link to say my index page or recent news page or whatever it takes me to the page but I get logged out and I have to login again. I've found out that linking between pages out works if the user's password is "something"
I have two versions of this site, the only difference is that they connect to different databases. On one domain everything works fine, on the other is when I get this issue.
This is at the top of every page for connections to the database and checking to see if the user has the right credentials and just some functions. I think the issue should be with the code checking the user credentials and or starting the session.
<?php
// Connect To Secure Login
$cfgProgDir = 'phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("includes/connect.inc.php");
// This file holds all the custom functions
include("includes/functions.inc.php");
This is the config file
$cfgIndexpage = '/index.php';
$cfgServerHost = '********************'; // MySQL hostname
$cfgServerPort = ''; // MySQL port - leave blank for default port
$cfgServerUser = '*********'; // MySQL user
$cfgServerPassword = '**********'; // MySQL password
$cfgDbDatabase = '******'; // MySQL database name containing phpSecurePages table
$cfgDbTableUsers = 'members'; // MySQL table name containing phpSecurePages user fields
$cfgDbLoginfield = 'firstName'; // MySQL field name containing login word
$cfgDbPasswordfield = 'password'; // MySQL field name containing password
$cfgDbUserLevelfield = 'permission'; // MySQL field name containing user level
// Choose a number which represents the category of this users authorization level.
// Leave empty if authorization levels are not used.
$cfgDbUserIDfield = 'id'; // MySQL field name containing user
/****** Data ******/
/* this data is necessary if no database is used */
$cfgLogin[1] = ''; // login word (username)
$cfgPassword[1] = ''; // password
$cfgUserLevel[1] = '0'; // user level
and the connect file ($connect) just connects the my DB
Any suggestions on what the issue could be? :)
It probably means your session is getting destroyed somewhere or cookies aren't being set.
I didn't dwelve much into the code (It's a bit messy) but... secure.php include checklogin.php on line 67. On checklogin.php file, Line 37, session_start() is called and it is called again on your config file.
It should raise a warning so, if you haven't seen it, you're either using an old version of PHP or you don't have error reporting enabled.
You should enable error reporting and check for any notice or warning.
I have a java script form in a website, that outputs some results -a silly simple mathematical operation or subtraction of dates.
I need these results to "remember" the visit so the div and the results
show when the user re-loads the page.
How can I achieve this?? It's my first time with facing a situation like this...
Note: its not a logged user!! but a non-logged visit..
http://goo.gl/OHQmpb
You can use localStorage.
Store the values in it by specifiying a key:
localStorage.setItem('key','value');
And, you can get the value by:
var value = localStorage.getItem('key');
HTML5 Web storage is the best option in your case.
Exact definition:
So what is HTML5 Storage? Simply put, it’s a way for web pages to
store named key/value pairs locally, within the client web browser.
Like cookies, this data persists even after you navigate away from the
web site, close your browser tab, exit your browser, or what have you.
Unlike cookies, this data is never transmitted to the remote web
server (unless you go out of your way to send it manually).
With HTML5, web pages can store data locally within the user's browser.
// Store it in object
localStorage.setItem("form attributes", "form values");
// Retrieve from object
localStorage.getItem("form attributes");
HTML5 Local Storage aka Web Storage can store values without maintaining a server side session. See this example:
function calculate(){
return 'some value';
}
window.onload = function(){
// submit handler for the form, store in local storage
document.getElementById("myform").onsubmit = function(){
localStorage.setItem('calcResult', calculate());
return false;
};
// load the value if present
var result = localStorage.getItem('calcResult');
if(result != null){
// show in div
document.getElementById("mydiv").innerHTML = result;
}
}