Optimizing local storage and search - javascript

I have a web application built in .NET
During a session, the user has to access a dictionary value, that is populated from the database. The user makes frequent calls to it.
I want to cut down the HTTP calls and want to bring the dictionary value to the client and access it from there.
I wanted to understand what would be the best practice to store this dictionary value locally in such a way that retrieving data is very quick?
What I'm trying to really do is similar to what FaceBook does with "#", so when you write #Name, it quickly makes a search in the database and replaces the text with the link. In my case, I have a fixed set of data to search from and usually it is not beyond 10-15 name-value pairs.
I contemplated of storing values in cookies, but don't really know if there would be any storage limit and am also unaware of how quick the retrieval would be.
Any help is much appreciated.
Thank You

If the dictionary is static then you can use JSON.stringify and localStorage to store it. This way the user only needs to load it the first time they ever visit your site. After it is stored in localStorage, I would suggest loading it into a JavaScript object using JSON.parse each time the page is loaded to speed up searching since a JavaScript object works like a hash table.
You could then add a simple check each time the page loads to see if the dictionary needs to be refreshed.
var globalDictionaryHash = null;
function loadDictionary()
{
if (localStorage.getItem("my_dict") == null)
{
localStorage.setItem("my_dict", JSON.stringify(myObjectFromAJAXCall));
}
globalDictionaryHash = JSON.parse(localStorage.getItem("my_dict"));
console.log(globalDictionaryHash['key']);
}

Related

Store user input data that can be accessed from other locations

For a project in my uni, I wanted to build a website that contained 200 messages and make it so that users can modify those messages, and then any other user who looks at the site would be able to see the modified messages and modify messages themselves. There would be exactly 200 messages, and the only way to make a new one is to override an existing one.
I've got all the user interface stuff functional and I've been tinkering with using the Google Sheets API to accomplish the string storage since it will handle JS arrays, but it doesn't seem to really be built for this type of use case.
If it would be possible to store the messages as strings (maybe in an array) in a document on the server and be able to use the javascript to make permanent adjustments to the strings in that document it would be amazing but I can't seem to find any sort of documentation on how to do something like that.
Does anyone know of any methods to approach a problem like this using JS and Jquery? Or know of an API they can recommend would be amazing.
Basically what I have already is a system that would call up the complete list of messages and store that as an array of strings.
var messagesIndex = (some sort of get function);
Then the user can select a message, and modify it, at which point the locally stored array is updated.
active = "(this is just here to make it a global var, it's just an index of which message I want from the array of messages)"
$(function() { $("button").click(function() {
active = this.id;
update();
});
});
function update(){
//sets the message inside the message display box to the correct message, where it can be altered
$("#message").messagesIndex[active]);
//some other stuff here that isnt relevent to this question.
}
and then the java would send that updated set of strings which would permanently override it in that storage doc. At least that would be my ideal situation.

Easiest way to store little information

I am quite new to coding so apologies if I'm asking an obvious question. I have managed to create a little web app in html/JavaScript that takes user input and transforms it and dumps it into a variable that I am interested in. All in all, all the information that I want to extract is in the form of an array comprising of 20 integers in the JavaScript code.
What I want to do now is find how to store that information so when somebody fills out the inputs and submits the form - I can have access to it. I have looked around the web and the common suggestion seems to be SQL database. I was just wondering if there is a simpler way of going about it, especially considering the tiny amount of information I need to store?
Well, if you just want to store the data on the website itself for each individual client, localStorage is the way to go. In other words, if you want to just store a bit of data for later, localStorage allows you to store data that is accessible the next time the user loads the page. This data can't be shared with other users, but if your app doesn't need too much security, or data sharing between users, localStorage is the way to go. However, the user can control what's in localStorage, so you need to make sure that you don't store anything sensitive there. In addition, you won't be able to see the data actually stored in localStorage on your website as the developer. All your handling has to be done on the client side. Every browser supports it, and it's really simple to use.
First off, you can set a value in localStorage like this:
localStorage.foo = "bar";
Then, you can get a value from localStorage like this:
localStorage.foo; //Returns "bar"
The only problem is, localStorage values can only be stored as strings.
So, in order to store an array (like you wanted to), you can do:
localStorage.arr = JSON.stringify([1, 2, 3]);
This turns the array into a string.
Then, to get the array from localStorage:
JSON.parse(localStorage.arr)
That's pretty much all you need to know for what you are describing.
If you want the full story on localStorage, visit: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I hope this answer helped.

Not allow localstorage to be changed by user

I use localstorage to store things like highscore in this game: http://wacky2048.ga/
If you inspect element and on the top navigation bar (where you see Elements ... Performance), then click the >> button, click Application, you can see all the localstorage items, and if you double click, you can change it. You may need to make a move and refresh.
A lot of people know this trick so the highscore becomes meaningless.
Is there any way to stop this? I store integers and JSON stringified things (in case you want to suggest a encoding method).
The better solution would be store the data in the server. But if you really want to use localstorage consider storing the JSON as a jwt token and encrypt it using a private key which user doesn't have access.
Also when your app access that data in the localstorage always check for validity. If the token is invalid, what you can do is re fetch the information from the server.
Like i said before this is more of a dumb approach. Storing data in the server would be a better solution.
Edit: To hide the private key you could use environment variables like NODE_ENV (this depends on the framework you are using)

How to keep a list of items updated on a website using Javascript?

Coming from Python/Java/PHP, I'm now building a website. On it I want a list of items to be updated in near-realtime: if items (server side) get added to or deleted from the list, this should be updated on the webpage. I made a simple API call which I now poll every second to update the list using jQuery. Because I need some more lists to be kept updated on the same page I'm afraid this will turn into more than 10 server calls per second from every single open browser, even if nothing gets updated.
This seems not like the logical way to do it, but I don't really know how else to do it. I looked at Meteor, but since the webpage I'm building is part of a bigger system I'm rather restricted in my choices of technology (basic LAMP setup).
Could anybody enlighten me with a tip from the world of real-time websites on how to efficiently keep a list updated?
You can use WebSocket(https://code.google.com/p/phpwebsocket/ ) technology.
but php is not the best language for implement it
A way to work this is using state variables for the different types of data you want to have updated (or not).
In order to avoid re-querying the full tables even if the data set in them has not changed in relation to what a particular client has displayed at any given time, you could maintain a state counter variable for the data type on the server (for example in a dedicated small table) and on the client in a javascript variable.
Whenever an update is done on the data tables on the server, you update the state counter there.
Your AJAX polling calls would then query this state counter, compare it to the corresponding javascript variable, and only do a data-update call if it has changed, updating the local javascript variable to what the server has.
In order to avoid having to poll for each datatype separately, you might want to use an JS object with a member for each datatype.
Note: yes this is all very theoretical, but, hey, so is the question ;)

client-side data storage and retrieval with html and javascript

I'm building what I am hoping to be a fairly simple, quick and dirty demo app.
So far, I've managed to build a bunch of components using only html and javascript. I know that eventually I'll hook-up a db, but at this point I'm just trying to show off some functionality.
In the page, a user can select a bunch of other users (like friends). Then they go to a separate html page and there is some sorting info based on the selected users.
So my first attempt was to put the selected users object into a cookie, and retrieve the cookie on the second page. Unfortunately, if the user changed their selection, the cookie wasn't getting updated, and my searches on StackOverflow seemed to say that deleting and updating cookies is unreliable.
I tried
function updateCookie(updatedUserList){
jQuery.cookie('userList',null);
jQuery.cookie('userList',updatedUserList);
}
but though it set the cookie to null, it wouldn't update it on the second value.
So I decided to put the selected users object into a form. Unfortunately, it looks like I can't retrieve the contents from the form on the client-side, only on the server-side.
Is there another way to do this? I've worked in PHP and Rails, but I'm trying to do this quickly and simply before building it out into something larger and am trying to avoid any server-side processing for now, which I have managed to do up to this point.
Since this is a demo, can you use HTML5? If so, you can use local storage: link text.
Another option is to use AJAX to load the other HTML page (replace whole body of the current document). Your storage variables would be stored in the <head>. This is a tightly coupled design, but again you're making a quick and dirty demo.
Is updatedUserList a string? If it's an array you might have to stringify it first:
jQuery.cookie('userList', JSON.stringify(updatedUserList))
(and of course parse it when you're retrieving it.)

Categories