I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('user')).name);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!
I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:
function getNextUnique () {
var next = localStorage.getItem('nextUniqueId');
next = next ? parseInt(next) : 0;
var newNext = next + 1;
localStorage.setItem('nextUniqueId', newNext);
return next;
}
Call it whenever you want to save a new user:
localStorage.setItem(getNextUnique(), JSON.stringify(user));
It makes more sense to use the user's email. Simplicity is good.
BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?
If so, then this is fine. But i wonder if you are really thinking about how localStorage works...
Related
I am working on a project where there is no user login system where people come and select multiple events they want to be in. From javascript, I wrote a code where if a user clicks it will store the id of an event in a javascript array but when I go to the checkout page the data gets cleared. So I came up with the idea of using localstorage of javascript. I have reached here:
var myData = '';
var livalue = [];
$('.party_a').on('click', function(e){
alert('One item added to the cart!');
sessionStorage.setItem("livalue", $(this).val());
alert(localStorage.getItem("livalue"));
myData = partyName.length;
if(myData == 1){
$('#cart').html("<li><a href='{{ route('checkout') }}'>My Cart<sup id='cart_number'></sup></a></li>");
}
$('#cart_number').html(myData);
});
But when I try to alert the livalue, it gives me null. Any suggestion on this matter is appreciated.
I have been trying to add data to my database without any luck.
In my code i have made a button when click, it will add data to my users database but it will not add it to the user but it just add the data outside like this:
is it because you cant add data when you have use the createUserWithEmailAndPassword() function?
Can anyone please show me how it is done?
btn.addEventListener("click", function()
{
firebase.auth().onAuthStateChanged(function(user)
{
if (user)
{
var massage = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.push(data);
}
});
});
Whenever you call push() Firebase generates a new unique ID. So to add the new data to the existing node, you should not call push. Instead you need to find a reference to the existing node for that user.
The easiest (and by far most common) way to do this, is to store the user data under the UID of each user.
Users
kHD...NoS
username: "bob"
Also note that there's no reason to put this type of onAuthStateChange listener inside a button click handler. Just attach it from the top-level JavaScript and it will trigger whenever the user signs in or when their auth state changes in any other way.
Alternatively, if the code really must run in response to the button click, there's no real use for a auth state listener and you can just check firebase.auth().currentUser:
btn.addEventListener("click", function()
{
if (firebase.auth().currentUser)
{
var message = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.child(firebase.auth().currentUser.uid).update(data);
}
}
Your code seems correct if you want to insert a new entry in Firebase database (just like your screenshot shows).
But, if you really want to sign up a new user, then you should be using firebase.auth().createUserWithEmailAndPassword() instead.
Finally, if you really want to update an existing node, see Frank response above ;-)
try this. you can change update to set. In your case something like
demo.update("users/KIK...fuA","display","my message");
//REVEALED METHOD TO ADD NODES WITH DATA TO REALTIME DATABASE
//eg, demo.update('mynode','myKey','myValue')
var demo = (function() {
var pub = {};
pub.update = function (node,key,value){
var ref = firebase.database().ref('/');
var obj = {};
obj[key] = value;
ref.child(node).update(obj)
.then(function() {
console.log('Update Ran Successfully');
});
}
//API
return pub;
}());
So basically i have a registration form and everytime the user registers, i store their data in HTML local storage, but i want the data to look like this for example:
user| [{"username":"Maximillian","password":"whatever","address":""whatever".... and so on. So far i have this code but i am confused with why it doesn't work the way i want it to. And how do i make sure that when another person registers, their details does not overwrite the current register details already on local storage?
You could store an array of the users. For example:
var users = JSON.parse(localStorage.getItem('Users')) || [];
var userData = [{Username:document.getElementById("UserName").value},
{Email:document.getElementById("EmailAddress").value},
{Password:document.getElementById("PassWord").value},
{Address:document.getElementById("Address1").value},
{Phone:document.getElementById("PhoneNumber").value}];
users.push(userData);
localStorage.setItem('Users', JSON.stringify(users));
Then access the users as such:
var users = JSON.parse(localStorage.getItem('Users')) || [];
users.forEach(console.log);
users[0];
users[1];
[etc.]
Is it possible to add to an existing integer stored in firebase. I am building an application that keeps track of a users word count by storing a key in their userId firebase key called wordCount:. I'm able to successfully update that key when the user clicks a button called "marked as read" but unfortunately it just replaces the integer instead of adding to it. Is it possible to get it to add to the value of the key wordCount: rather than replacing it.
Here is the code inside one of my controllers. Side note, angularAuth.getAuth just checks to see if the user is logged in or not
this.markedAsRead = function(wordCount){
if(angularAuth.getAuth){
var userBase = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.update({
wordsRead: wordCount
})
}else{
console.log('please log in to use this feature')
} }
I was able to get it thanks to an idea of #manube
this.markedAsRead = function(words){
var userBase = $firebaseObject(new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid))
var users = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.$loaded().then(function(data){
self.count = data.wordsRead
users.update({
wordsRead: self.count+words
})
})}
I have this fiddle: http://jsfiddle.net/y8Uju/5/
I am trying to save the numbers, because, when I submit, the list of numbers gets erased. I am a little new to JavaScript so am not quite familiar to what is available. In PHP I would use sessions to save the list, but what can I do in JavaScript to do this?
Here is the JavaScript code:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("input");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByClassName("inputNames").length;
var newGuy1 = document.createElement("input");
newGuy1.setAttribute("class", "inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
function deletename(name) {
if (name.value == "") {
document.getElementById("names").removeChild(name);
}
}
You can use localStorage: http://jsfiddle.net/y8Uju/8/
Loading:
var saved = JSON.parse(localStorage["numbers"] || "[]");
for(var i = 0; i < saved.length; i++) {
document.getElementById("name").value = saved[i];
add(false);
}
Saving:
var saved = JSON.parse(localStorage["numbers"] || "[]");
saved.push(num1.value);
localStorage["numbers"] = JSON.stringify(saved);
And define the function of the addName button separately, so that you can call it when loading as well.
Edit: You have to execute a function when the page is loading to fetch the stored numbers, and add some code to save the entered number when one clicks the Add button.
For storing you can use localStorage, but this only accepts Strings. To convert an array (an array containing the entered numbers), you can use JSON.
When loading, you need to add the numbers just like happens when the user fills them in. So you can set the name input box value to the saved number for each element in the array, and then simulate a click on the Add button.
So you need an add function that is executed when:
User clicks Add button
Page is loaded
However, when simulating the click the numbers should not get stored again. You need to distinguish between a real click and a simulated one. You can accomplish this by adding an argument to the add function which represents whether or not to store.
Not entirely sure what the question is, but one problem I see with the code - id's can't be numbers, or start with numbers
var nameOfnames = form1.getElementsByClassName("inputNames").length;
//....
newGuy1.setAttribute("id", nameOfnames);
That might be slowing you down somewhat. Perhaps set id to 'newguy' + nameOfnames
Jeff, the reason that the page keeps getting erased is because the form submission triggers a page reload. You need to place a listener on the form submit event and then send the data through AJAX. This way the data is POSTed to "text.php" without reloading the page with the form.
You could place the values in a cookie but that is not ideal because you have a fairly limited amount of space to work with (4kb). I also get the feeling that you're trying to hand them off to some server side script so HTML5 local storge wouldnt be a good solution, not to mention that your eliminating over half of the people on the internet from using your site that way.
Since browsers are inconsistent in how they attach event listeners AND how they make AJAX requests. I think that most people would recommend that you use a library like jQuery, dojo, or prototype which abstract the process into one function that works in all browsers. (my personal fav is jQuery)
There are a few options available to you:
Save it client side using cookies (http://www.quirksmode.org/js/cookies.html)
Save it client side using HTML5 local storage (http://diveintohtml5.ep.io/storage.html)
Save it server-side using Ajax
The Ajax solution involves a server side page (in PHP for example) that reads a request (a POST request for example) and saves it into a database or other. You then query that page in JavaScript using XmlHTTPRequest or your favorite library.