Multiple values in lawnchair - javascript

I'm using Lawnchair, and I've managed to store a value locally. Something like this:
var Users = new Lawnchair({table:'Users', adaptor:'dom'});
function save_prompt()
{
var UserName = prompt("Your Username","John Doe");
if (UserName!=null && UserName!="")
{
Users.save
({key:'UserData', SavedUserName:UserName});
}
}
function recall_prompt()
{
Users.get
('UserData',function(r)
{
document.getElementById('Message').innerHTML = r.SavedUserName;
}
);
}
I call both functions save_prompt & recall_prompt using buttons binded with onclick.
Basically this script will pop up a textfield to enter your username (John Doe is default) and saves it.
With recall_prompt, it worked fine by showing the saved username in the html div id="Message".
My question is, how to save a second, third, and beyond usernames? And how to retrieve them all to show in the html div? I've tried numerous methods that can be found on the 'net but I just can't get it to work. It seems the new username always overwrites the old ones.

Lawnchair saves data as Key:value pairs. So if u save another username with the same key, (UserData), it'll always get overridden. To save more usernames u'll have to change the keys. Make it UserData_1, UserData_2, like that.
Or you could store an array of usernames with the key 'UserData', so each time u need to save a username, get the array from DB, then add the new username to it and resave it.

Related

JavaScript (Discord) Is there a way for my bot to store values and then repeat?

I have my current Discord Bot project using JavaScript however i cannot find a way to store the value itself when done through a command such as !setname ___ hoping for a response of that being repeated back when I use !myname.
I know how to do it by storing it temporarily through:
bot.on('message', function (user, userID, channelID, message, evt) {
if(message == "!myname") {
bot.sendMessage({
to: channelID,
message: 'Your name is ' + user.username;
});
}
}
However i cant figure out how to do it through the ability to call for it whenever you want rather than getting an immediate response. For example setting my name now but being able to have it output when i use the command instead of having command that sets the value then outputs it in an immediate string
Would recommend a simple key-value dictionary style in the current instance.
(Though you could store it to a text-file or database later if you prefer the data to be persistent across different sessions.)
Instance based:
Based on this post on stackoverflow...
You can create a global dictionary at the top var usernameChangeDict = {};
Whenever the user invokes !setname, just do:
usernameChangeDict[user.id] = Their_new_name_here
Fetch it back using usernameChangeDict[user.id], should return null or empty if they did not set their name before.
Persistent data:
Could either store it in a text file on your local computer, or do a database as Zooly mentioned.(Though personally, a database would be an overkill if your bot is not going to be used by a wide range of people.)
Text file
Read from this post, it contains details on how to write onto a text file.
This post talks about reading from a text file.
I would recommend storing it in a JSON format to make your life easier, since JSON.parse exists.
Most likely you would end up storing in a format like this:
{ "23125167744": "someone", "USER_ID": "username" }
Access it by parsedJson["USER_ID"].
SQLite
This tutorial would probably explain how to set your SQLite for javascript better than I do.
Once its all setup, just store the userID and username, you can just do:
SELECT username FROM yourTable WHERE userID = ?;
and
INSERT INTO yourTable (username, userID) VALUES (?, ?);
For inserting and selecting into database respectively.

How to store sessionStorage as a variable so it can be stored in a database

I need to store the email of a logged in user, which I have stored into
sessionStorage with the line of code:
sessionStorage.setItem("loggedInUser", $("#email").val());
But in a different program, I need to store the email as something so that it can be sorted and posted to a php file that inserts it into my database. Here is my javascript so far.
$(document).ready(function () {
//When the submit button on the recruitment form is pressed.
$("#SubmitRecruit").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.loggedInUser;
var forename = document.getElementById("forename").value;
var surname = document.getElementById("surname").value;
var jobType = document.getElementById("jobType").value;
var phoneNo = document.getElementById("phoneNo").value;
//create an array with the details in.
var recruitdetail = {
email: email,
forename: forename,
surname: surname,
password: password,
phoneNo: phoneNo,
}
//log the forename in the console so that we know that the register has been successful.
console.log(email)
//direct the user to the login page and alert them that their registration was successful.
window.location.href = "../index.html"
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", JSON.stringify(recruitdetail)
)
}
})
On the 5th line I tried to make it equal to sessionStorage.loggedInUser with no avail. I know I need to store email as something from session surely, as then it will be passed back into php and stored in db, but I cannot figure out what or how to do this. Any help will be greatly appreciated.
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
To get the item from session storage try using the getItem method:
var email = sessionStorage.getItem("loggedInUser");
See sessionStorage documentation.
For the ajax request, just pass the object directly to $.post and put the alert in the success callback so it only shows when the request completes successfully:
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", recruitdetail, function(data) {
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
});
As a side note - if you have a table of users/logins, the email of each user should stored in that table. The foreign key between your users table and other tables would then be an (auto-incrementing) ID, rather than an email address. This makes the system much more flexible (email can be changed, etc).
If by different program you mean different application on different domain, then you can try sending the email value through an AJAX request to be stored in the PHP session.
If on the same domain but just a different app running in a different tab, then you can use localStorage, with the same syntax as sessionStorage. Note that sessionStorage data is limited to the tab in which it was set.
localStorage.setItem("loggedInUser", $("#email").val());
and then
var email = localStorage.loggedInUser;
Or you can use cookies.
https://www.w3schools.com/js/js_cookies.asp

Linking to elements within different documents

I have used the 'prompt' method into asking for a character name. however i am wandering if i can save that data to then use again in different html documents, to use the characters name in context. I am currently using Javascript and would like to try and use that to solve this issue.
You can use localStorage to access the data input by user on another page (must be same origin).
var value = prompt('Please enter your name');
if (value) {
localStorage.setItem('username', value);
}
To get the saved data on another page, use:
localStorage.getItem('username');
Just assign a variable prompt function. The user input will be saved in this variable.
var saveMe = prompt('What time is it?')
console.log (saveMe)
If you want to store data and use them only locally you should maybe use the local storage, this allow you to save data into the user's browser. But you should know that old browsers do not support that.
Look at the W3School class about local storage.
Here is an example of how it works :
localStorage.setItem("userName", prompt('Your name'));
And then when you need to access it :
localStorage.getItem("lastname");

about local storage.getItem()

I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start

Undefined attributes in Parse

I'm using Parse to handle my backend and I'm encountering issues grabbing data from my Parse objects. I've seen many questions similar to this, but none with a straightforward answer.
My User objects have a field called groupsArray which is an array that contains Group objects. Each Group object then contains a field called groupName, which is simply the name of that particular group object.
Here is my trouble. I'm grabbing the current user via
var user = Parse.User.current();
then I grab the groupsArray and the groupNames via
var groupsArray = user.get("groupsArray");
var groupName = groupsArray[i].get("groupName");
Initially this works after I add a group, however, my problem comes after I refresh my browser. After refreshing my browser, all my groupName fields are undefined. When I try and grab their id, it works, but all the personal fields that I created for that object is undefined. When I go to my applications dashboard on parse.com, I see all the objects with their groupNames. Anyone know what's going on?
More detailed code:
Inside groups.js, which calls modelGroups.js:
$('#tester').on('click', function() {
populateSidebar();
});
Inside modelGroups.js:
function populateSidebar(){
var groupsArray = Parse.User.current().get("groupsArray");
for (var i=0; i<groupsArray.length; i++) {
var groupName = groupsArray[i].get("groupName");
console.log(groupName); // ALL of these are undefined after a browser refresh
}
}
And yes, even after refreshing the browser, Parse.User.current() is fetching the correct user, user.id, and username
It seems that the group data needs to be fetched from database again after refresh to me. Never happened on iOS since I enabled local datastore for me.

Categories