Best way to save javascript data in localstorage - javascript

I want to be able to create JavaScript note objects and dynamically delete them using a navbar pane.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var editor = { "startContainer": range.startContainer, "startOffset": range.startOffset, "endContainer": range.endContainer, "endOffset": range.endOffset };
Then using a message I would pass the location and message into a function to add notes:
Notes(editor, message);
function Notes(location, note) {
this.location = location;
this.note = note;
}
I'm trying to wrap my brain around how to actually save the data locally.
function addNote() {
// if(tyepof(Storage) !== "undefined"){
// if(localStorage.notes){
// localStorage.notes
// } else {
// localStorage.notes =
// }
localStorage.setItem()
}
Is localStorage the way to go? I know sessionStorage only stores for a session.

Here's a quick way to generate a few elements from a localStorage.getItem() call and could maybe also help you out here along with Nelson's answer. Click on the button in the fiddle and you'll see the code grab the localStorage objects and use them to create some simple <li>'s.
Fiddle:
http://jsfiddle.net/kfrvdnux/
Example code:
HTML
<button id='save'>Click the save button...</button>
<div id='content'></div>
JS
var content = document.getElementById('content'),
save = document.getElementById('save'),
output = '<ul>',
animals = [{
name: 'bob',
type: 'dog'
}, {
name: 'fred',
type: 'lizard'
}];
// set on load for testing
localStorage.setItem('animals', JSON.stringify(animals));
// grab localStorage data on click and create a list
save.addEventListener('click', function() {
var ls = JSON.parse(localStorage.getItem('animals'));
for (var i = 0; i < ls.length; i++) {
output += '<li>' + ls[i].name + ', ' + ls[i].type + '</li>';
}
output += '</ul>';
content.innerHTML = output;
});

You have many ways of doing this. In fact so many that is not praticable to explain all of them. It depends on you actual intent. If you just want notes you can loose aftwards, localStorage may be the way to go.
But for most applications you typically would do this sending data to a server that would be responsible for storing the data. In the server the data could be stored in a database, in local files, there are many ways.
Servers could be Node.js (if you want to stick to js only), or any other language that has server capabilities. That would be pratically all. Most used are Node, PHP, Python, Java and others.
You would prepare a certain url to receive a post with the data that needs to be saved and then make the client send an ajax request to this url with it.
in this question you can get some examples of how to start doing this:
Basic Ajax send/receive with node.js
the server save part is up to you :)
edit
here is a small tutorial about localStorage
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
just remember that every time you reload the page you will loose everything. In order to save the data you have to send it to a server.
Another thing: you don't need to buy a dedicated server to do this. You can implement the server in your own machine. This is a relatively easy task. Not that complicated. I advise you to take a look in the SO question above about basic ajax send/receive, before you rule this out.

Are you trying to save .txt files locally to the computer? I don't believe JavaScript has this function because it would be a huge security hole. My understanding is that you could create cookie files on the local machine but that is about it.
If you need to export files you could always use an ASP.NET/PHP to create files on a server, then the user could click on a link that would prompt you to save the dynamically created file.
Based on the comment below you should create an array of objects.
var array = [];
array[array.length] = {name: 'NAME CONTENT', other: 'Other content', number: 1}
array[array.length] = {name: 'NAME CONTENT 2', other: 'Other content 2', number: 1}
You can then get a function to do things with your object by doing something like this
PrintInfo(array[i]);
function PrintInfo(aSingleObject){
console.log(aSingleObject.name);
console.log(aSingleObject.other);
console.log(aSingleObject.number);
}
To remove objects from your array using the splice command
var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);

Related

Looping through HTML form data via JSON arrays/objects?

I have been scouring this website and the internet for a few hours now, and asked a question earlier which got me at least a step further.. However I am really struggling to understand how to save multiple arrays to my localStorage.
I can understand the process using a hardcoded array, but as soon as I try to implement the localStorage data, I can't understand what to do.
Heres what I have tried so far (with help from another SO user):
$("#submit").click(function () {
// prepare
var formData = $("#regForm").serializeArray();
// get all stored as Array []
var bookings = JSON.parse(localStorage.getItem('bookings') || '[]');
for (formData = 0; formData < localStorage.length; formData++) {
// insert and save
localStorage.setItem("bookings", JSON.stringify([formData]));
}
});
It works fine without the for loop, however when I resubmit the form with new data it replaces it rather than creates a new index?
Basically I am trying to create an appointment scheduler for dog walking and I need to be able to view each booking, amend, delete, and of course view the bookings (all client side - no databases).
Should I be initialising my array first? How to I approach the for loop? Any help is appreciated as I want to learn but I have been at this for hours with no luck.
You can use like following.
Save new values in the the previously stored values in variable and update the local storage at the end.
$("#submit").click(function () {
var formData = $("#regForm").serializeArray();
var bookings = JSON.parse(localStorage.getItem('bookings') || '[]');
for (formData = 0; formData < localStorage.length; formData++) {
bookings.push(formData)
}
localStorage.setItem("bookings", JSON.stringify(bookings));
});

How do I rewrite the JSON object in a file using file system in Node Js

I have came across the read and write operations using fs in Node Js.
My scenario is like, I have a file having the data like ,
[
{
"Pref":"Freedom",
"ID":"5545"
},
{
"Pref":"Growth",
"ID":"8946545"
}
]
I have to replace the Pref of the element whose ID is 5545 using Node js.
How can I do it. Thanks
To do what you want, you wound need to:
read JSON data from the file with fs.readFile()
parse the JSON with JSON.parse()
find the correct object in the array
change the object
serialize the object back to JSON with JSON.stringify()
write the file with fs.writeFile()
but this is not that simple as it may look like, because you will have to:
add locking to writes so that you never do two writes at the same time
add locking to reads so that you never read while the write is in progress
handle incorrect JSON
handle cases of objects that cannot be serialized
avoid blocking operations (those with "Sync" in their name) anywhere else then in the first tick of the event loop
Considering all of that you should consider using a database to store any data that changes. Some databases like Mongo, Postgres or Redis need to be run as standalone application either on the same or on a different server. Some embedded databases like SQLite don't need a standalone process and can be run directly in your application.
It's not that it is impossible to write to JSON files and then read those files as needed, but the amount of work that you'd have to do to synchronize the access to the data all without accidentally blocking the event loop in the process is much more difficult than just using any database as intended.
You have some data:
const data = [
{
"Pref":"Freedom",
"ID":"5545"
},
{
"Pref":"Growth",
"ID":"8946545"
}
]
First we need to find the element you want to change (use [0] to only select the first in case there are multiple items with ID 5545:
const objectToChange = data.filter(item => item.ID === "5545")[0]
And then change it!
objectToChange['Pref'] = "Liberty"
We can see the change reflected in the data object:
console.log(data)
// [{
// ID: "5545",
// Pref: "Liberty"
// },{
// ID: "8946545",
// Pref: "Growth"
// }]
1- Load file: let json = JSON.parse(fs.readFileSync('file.json', 'utf-8'));
2- Update content:
json = json.map(el => {
if(el.ID === "5545") {
el.Pref = "TEST";
}
return el;
});
3- Save again maybe?
fs.writeFileSync('test.json', JSON.stringify(json), 'utf-8');

How can I redirect with extra information in jquery?

I'd like to perform a redirect, but I also wish to send additional information along with it.
I've tried to change the value of window.location.href but that doesn't seem to pass along the extra information.
I also get how I can do
$.get(
new_url,
{data : "mydata"},
function(data) {
alert('page content: ' + data);
}
);
and that will display the html content of the new page, but that doesn't help with actually getting there.
How can I achieve this?
Edit: I feel as if I must be phrasing this terribly because I'm pretty sure this is an easy/common task. This shouldn't be something that would require cookies - it should basically be like a post request (I think).
You have a few different options for this:
URI Variables - You can append extra data to the URL by appending a question mark (?) followed by a set of key-value separated by an ampersand (=) with each variable being separated by an ampersand (&). For instance, http://www.google.com/search?q=javascript+url+variables&ie=UTF-8 gives you a link to a Google search for "javascript url variables" using UTF-8 encoding. Your PHP code or JavaScript would need to handle passing along and processing these variables. If using JavaScript a nice library for processing URLs is URI.js or using PHP you can use the parse_url and http_build_query functions. You can use this with window.location.href; for instance: window.location.href = "http://www.google.com/search?q=javascript+url+variables&ie=UTF-8" (replace the Google URL with the one you created or set in a variable).
Storage API - You can use the localStorage or sessionStorage properties to store and retrieve information using JavaScript (information is stored in the user's browser - supported by IE 8 and newer and all other major browsers). Note that this is JavaScript only unless you grab the data with JavaScript and pass it to your PHP server through URL variables, form, AJAX request, etc.
Cookie - You can store additional information inside a cookie - however this is more difficult since you have to setup your variables as a parsable string (possibly JSON) and remember to encode/decode the string when setting/getting the cookie. I don't recommend this method.
IndexedDB API - This is a more advanced client-side/browser storage mechanism and currently only supported in IE 10 and newer (and nearly all other browsers). There are also still changes being made to the standard which means newer versions of browsers could break current implementations or be buggy. If all you need is simple key-value storage (not an SQL-like database) then you should stick with one of the above options.
You can use the window open method to redirect your user,and remember to use "_self"
window.open('url','_self');
Preferably you'd store the data in localStorage and fall back to a cookie (I really like js-cookie).
Here are the two helper functions you need to store and retrieve data:
function setMultiPageData(itemName, data) {
var dataStr = JSON.stringify(data);
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
localStorage.setItem(itemName, dataStr);
}
else {
Cookies.set(itemName, dataStr, { path: '/' }); // path set to root to make cookie available on any page
}
}
function getMultiPageData(itemName) {
var data = null;
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
data = localStorage.getItem(itemName);
}
if (!hasLocalStorage || data === null) {
data = Cookies.get(itemName);
}
var parsedObject = null;
try {
parsedObject = JSON.parse(data);
}
catch (ex) {
console.log(ex); // remove in production
}
return parsedObject;
}
usage:
var data = { first: 'this is the first thing', second: 'this is the second thing' };
setMultiPageData('stackoverflow-test', data);
// go to a new page
var retrievedData = getMultiPageData('stackoverflow-test');
if (retrievedData === null) {
console.log('something went wrong')
}
else {
console.log(retrievedData); // { first: 'this is the first thing', second: 'this is the second thing' }
}

How can I access variables from a JavaScript file from within a script I wrote in an HTML file?

So, I'm making a super basic (and also not secure, because I'm just playing around right now) login system that displays different values for premade graphs based on who you are. I'm accessing the data for the graphs from a JSON with an array of objects that contain things like username, password, number of students, number of students that are boys, girls, etc. I want to have an ID variable that is set in my login page when the person logs in with credentials that match one of the objects' username and password in my JSON file. (the ID would be the index of whatever object the credentials matched). When I make the graphs in my HTML file using chart js, I'm opening the JSON file and accessing one of its objects by that ID and accessing its contents that way. I'm struggling to find a way to reference this ID that is in my JavaScript file in my HTML code "scriptlet", if that's what it is called. Also, I DID try to include the JavaScript file in my html file, but I keep getting errors when I try to reference it in the html how I have in my snippet. Here's a sample of my code:
var objectID; //this is the ID I'm talking about in my question
function clickedLoginButton(){
var script = document.createElement('script');
script.src = 'jquery-2.1.4.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var user = document.getElementById('username'); //inputted username
var pass = document.getElementById('password'); //inputted password
var passed = false;
$.getJSON('data.json', function(data){
console.log("Length: " + data.length)
i = 0;
do{
console.log(data[i].login);
if(user.value == data[i].login && pass.value == data[i].pass){
objectID = i;
window.open("http://localhost/loggedIn.html", "_self", true);
console.log("pass");
return;
}
i++;
}
while(i != data.length);
if(passed == false){
window.open("http://localhost/loginFailed.html", "_self", true);
objectID = 999999999;
console.log("failed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script> //This is where I want to use the object ID
var numPlayed;
var numLazy;
$.getJSON('data.json', function(data){
var chartData = [
{
value: data[objectID].numStudents-data[objectID].numStudentsPlayed,
color: "dimgray",
highlight: "gray",
label: "lazy"
},
{
value: data[objectID].numStudentsPlayed,
color: "skyblue",
highlight: "powderblue",
label: "played"
}
];
var ctx = document.getElementById("pieCanvas").getContext("2d");
var piechart = new Chart(ctx).Pie(chartData);
});
</script>
I figured it out! You have to use cookies to access the ID for the user, and here's a tutorial for that:
http://www.w3schools.com/js/js_cookies.asp
The problem is that once you set the objectID variable, you navigate away from the page. Once you navigated away from the page, you can no longer access JS variables defined in the previous page.
To go around this problem, you can store the value of the objectID so that the next page can access it again. You can do this using several methods.
Using query parameters of the next page.
When redirecting to the logged in page, you can specify the objectID.
window.open("http://localhost/loggedIn.html?objectId="+objectID, "_self", true);
Then, in the script in the loggedIn page, you can access the objectID using window.location.search
console.log(window.location.search); // outputs ?objectId=2343
Using localStorage
You can use localStorage to store the value of objectID. localStorage.setItem('objectID', objectID) then extract it in the logged in page using localStorage.getItem('objectID').
Using Cookies
As you mentioned above, you can use cookies to store and extract the value of objectID. The disadvantage of this is that it is sent in all subsequent requests to the server.

Adding to localStorage with JavaScript and Jade

Having issues with Jade and the way the data is passed to it when it is rendered.
I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}];
format but having issues as it shows up as the result below.
Result
key: xyz value:[{"artist":"Lady Gaga",...
This is the code I am working with on the server-side Node.js which is passing it fine ...
res.render('musics', {
title: 'site',
result: JSON.stringify(result)
});
This is the code I am having issues with because of the way I have to call result in jade...
script
function local (arr) {
var i;
i = "#{result}";
localStorage.setItem('xyz', i);
}
console.log('stored');
local();
The quotes around result are messing it up but without them I get an error for unexpected identifier...
Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.
your jade snippet should look like this then:
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"
by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.
As an improvement to #greelgork's answer:
This is for JSON array
script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"
Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, #greelgorke's answer should be modified so:
single item
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"
So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx
Credit Push JSON Objects to array in localStorage
if usersList.length
script.
const userList = !{JSON.stringify(usersList)}
localStorage.setItem('xyz',JSON.stringify(userList))
const loader = document.querySelector(".loader");
loader.className +=" hidden";

Categories