Multiple cookies with javascript, stategies anyone? - javascript

LocalStorage doesn't work here. I am looking for more of a theory type answer and not as much code. I already know how to set and delete cookies, that is now what this question is about; here is the question:
When I submit an order, I want to place
Meal
Ingredients
Name
Phone
inside cookies to be later outputted on a div to the right of the page. This I think I can do quite easily. I might put each value into an object of orders...
But that isn't the real question, how can I have multiple orders that are unique? I want to have many different orders and have the user delete the order they desire. I was thinking of separating each order with a | character and than playing some string games. But I don't know how I would delete one.
My other idea was have a order id and auto-increment it. Any help? website: philipimperato.com/mobileOrder
P.S. Only Javascript and I know how to setCookie and deleteCookie :D

Cookies don't seem the place do to this anymore. Cookies are limited and are sent with each HTTP request, including all of your images and static files unless they are on a different domain. I recommend using localStorage instead. Since this is intended for smartphones like the iPhone and Android you are ok to use localStorage. Webkit browsers have supported it for a long time. If you use localStorage you can use any kind of key value storage mechanism you like. I recommend the redis way of field:id:property for keys.
var order_id = 10203;
var key = 'order:' + order_id + ':drink';
localStorage[key] = 'Pepsi';
By using the order_id in your key field you can easily manage unique orders.

You could serialize an order object array in json and parse it back as you load
(This could present security issues, and maybe you should use a framework to parse json back to life. Many frameworks do some lint on json before evaluating it, some even parse it all by themselves)

Related

Is it possible to send localStorage data, and then retrieve it again? AJAX?

My scenario is this: I have a very small array in my js file. When the page loads up, I have a function that loops through the array, and generates an li element for each item in the array, displaying it's name and price in the li. The array is constructed like this:
var gameList = [
{ name: "", value: 0.00},
]
Secondly, I have a simple form on the page that allows me to add new items to the array, and using localStorage, it's possible for me to keep a dynamically updated array. I push new items into the array (gameList), then at the end of the session I set it using localStorage.
localStorage.setItem("updatedGameList", JSON.stringify(gameList));
I have a couple of lines at the start of my code that sets my original array 'gameList' to be equal to the locally stored, updated game list.
var retrievedData = localStorage.getItem("updatedGameList");
gameList = JSON.parse(retrievedData);
So this is fine for now, but the growing array - which I want to keep and maintain - is only available in this browser, on this machine.
So, my question is, can I send this locally stored data somewhere? Maybe my personal domain? (Which is where I will host the app when it's finished) That way I could then reference it properly in my js file so that the data is always available? Maybe the array could have it's own js file?
I realise that this may not be the best way to be handling what is essentially a database. But I'm only part way through an online course and I'm using the tools that I have to make this work.
And lastly, in terms of maintenance of the array, is there any way to send it back to sublime in the form a .js file? I know this could be a crazy question. The updated array will become pretty big, maybe 200 items eventually, and it would be much easier to maintain from within sublime.
Thanks for your time, and apologies if part of this request is ridiculous!! :)
I have just been reading about AJAX, and thought maybe there's a way to send the updated array as a json file to somewhere(!) on my website, and then request that same file at the start of each new session, so I'm always working with, and saving, the latest updated array.
Thanks for reading, and hopefully you have some answers! :)
Although not quite what I was looking for - essentially some way of automatically getting the new array, sending it somewhere more secure than local storage, then referencing the new array to give me the most up to date starting point each time (and all with just javascript) - the 'dirty' way suggested below turned out to be sufficient for now until I start using databases.
From Kirupa, over at the forums:
Not a ridiculous question at all! You can send your own data anywhere you want, but it will require some level of server-related code. The easiest way to send data back and forth is through JSON, and you can convert your array into a JSON format easily using something like the following:
var jsonData = JSON.stringify(myArray);
From here, you can send this data to a database, to another web site, or to your e-mail server. If you want something really quick and dirty, you can literally just copy the contents of your JSON-ized array using the Chrome Dev Tools, save it on disk as a .js file, and reference it again in your app. That is a manual way of doing something that you don't really care about automating.
The best solution is to store this in a database. They've gotten easier to deal with as well. Firebase is my go-to for things like this, and this video might give you some ideas: https://www.youtube.com/watch?v=xAsvwy1-oxE

How to avoid reloading large JavaScript array?

I have a large 40,000 words array loading from a database into a JavaScript/HTML array on every page of our web application... What would be the best way/technology to optimize it? In order to avoid this unnecessary downloads.
Somehow keep the array in a cookie and read from there?
Use ajax to load the array dynamically only parts that are needed?
What is the common practice?
On modern browsers you can use sessionStorage to have it persist during the current session, or localStorage to have it hang around between sessions.
NB: both only permit storage of strings - you'll have to serialise the array (e.g. into JSON) and deserialise it on retrieval.
If you want to actually use the word list as a local database with efficient lookup you might also want to investigate indexedDB
you can place the data in session and retrieve it, the same can be used in every page with out fetching the same every time.
Thanks & best regards.
If you need all the 40k words in all pages then you can use localStorage or sessionStorage. Just keep in mind sessionStorage will delete saved data when the tab/window is closed so the whole array will be downloaded again when the website is opened in new windows/tabs.
If you need only specific parts of the array in different pages I would tidy the array's elements into taxonomy/categories (if you are able to), so that you can download only the needed for a specific section of your application.
This depends on the composition of your array, if it is formed only by words or complex objects. This will help to avoid slow load of your website when it's visited the first time.
If the array is always the same (there is no need to update it), I'd create a js file and then I'd add it to every html page. The browser's cache would do the rest to avoid unnecessary re-loading. Something like:
big-array.js file:
var myBigArray=[...]
In each html file
<html>
... whatever you need
<script src="/my-path/big-array.js"></script>
...my other scripts here
</html>
It's a bit difficult to answer this question properly as to do so would require more information about your hosting environment and what you have access to. If you have a server side language available, such as PHP, you could look at caching which is generally the most efficient way to handle data that is used repeatedly across pages. Perhaps you could post more info about what technologies you have available to you?

Saving Settings as JSON in Database vs Saving them in extra rows

I have settings of users, which I would like to save in the Database.
The question is now, whether or not I should make for each setting a new row, OR save them in a JSON.
What is the best way to go with, strategic- and habitwise?
Depends on several things:
How many settings do you have?
Do you expect them to rapidly change - both creating new settings and deleting old settings?
Do you need to search for users with specific settings?
Basically, JSON is more flexible and is good if you have lots of settings or if your list of settings is rapidly changing.
Fields are conservative but working with them is way faster than unpacking JSON.
Most often for user settings I would use one field per setting. The reason is that it allows easily getting a list of users with specific setting set (same age, same sex, same city etc.), also ordering them and so on.
But you can use both these options at the same time.
For example, put username, password, firstname and basic options as fields. Then you can quickly get the answers to the questions like "Is this username unique?" "is the password valid" etc.
At the same time you may create a field "additional_options" that will be json-encoded field for some not-so-often-used data, like "about me" and answers to secret questions.
JSON is a way to encode objects, or just serialize data in an easy fashion.
If you plan on saving the data and reading it not very often then JSON sounds like a good clean way, easy to upgrade later when you have more settings. If you plan on writing and reading this data a lot then you will have a big overhead of serializing and de-serializing the data and I would not recommend this.
The question is tagged as javascript, so I assume you are consuming them from js. In this case and assuming they are a small number of key-value pairs, and that you probably read them all together (ie you are not querying them individually or comparing their values for different users or things like that), then storing as json is the better option in my opinion.

javascript, html onclick change variable

I have a series of links, each belonging to different products with different prices.
Eg:
<%a class="items" href="order.htm" alt="" onclick="javascript: num = 149.99">Content<%/a>
After a user clicks one of the product links, I would like to be able to display the price of that specific product on the Order page. Is it possible to hold the changed variable for use on the separate Order page? If so, how?
This is purely for my personal exploration into JavaScript and HTML5.
Edit: Okay, so using sessionStorage, I can set and get variables.
Eg:
myVar = window.sessionStorage;
myVar.setItem("key", "149.99");
Now, how would I integrate the var with the product link, then call that var on the following page?
If you are creating a shopping page, I would definitely recommend you to include some PHP.
With only JS and HTML, you will encounter many problems you will have to find a workaround for.
Use a server-side storage like PHP's $_SESSION superglobal. Any client storage could get manipulated. You are saying you aren't publishing it, but keep it clean anyways and don't learn yourself the worse way.
Anyways, if you just wanna get this working, here are the commands to store the data and get it afterwards:
//store data on the initial page using setItem()
sessionStorage.setItem("mykey", "Some Value");
//on the next page get it with getItem() and declare it as a var
var persistedval = sessionStorage.getItem("mykey");
­
//Now you can write the price to the document using the variable
document.write("Total is: " + persistedval);
Values can be set and retrieved using either getItem() and setItem(), or by directly referencing the key as a property of the object, like in my example above.
But remember, sessionStorage isn't very safe, since it's stored in the browser session.
Imagine you even forgot your price validaton check and some 'hacker' manipulates the data and changes the price from 45,99 to -249,99 and the product name to Credit note.
If you want to go deeper into shopping pages, user areas, etc. you should concentrate on HTML+PHP at first and just use JS when you need it (which will be mostly DOM-Manipulation when you start off).
But it's great for storing a user login, any user-specific data or insensitive data, no question about that.
Hope this helps.
You could store your cart using localStorage
JavaScript has no notion of state, so by itself it cannot persist information across pages. However, there are several different ways that we can remember data from one page to another.
We could use a cookie if really really have only a very small amount of data to store and want to support old browsers.
Another way to do it would be to use LocalStorage to store the information. This gives a much greater amount of storage space and has a flexible and easy to use format to set and retrieve the data.

How to make a local offline database

I'm making a to-do list application with HTML, CSS, and JavaScript, and I think the best way for me to store the data would be a local database. I know how to use localStorage and sessionStorage, and I also know how to use an online MySQL database. However, this application must be able to run offline and should store its data offline.
Is there a way I could do this with just HTML and JavaScript?
Responding to comments:
"You said you know how to use localStorage... so what seems to be the problem?"
#Lior All I know about localStorage is that you can store a single result, as a variable whereas I wish to store a row with different columns containing diffenent data about the object. However, can localStorage hold an object and if so is it referenced with the usual object notation?
Any implementation will probably depend on what browser(s) your users prefer to use.
#paul I think chrome will be most popular.
Okay, I would like to clarify that what I was asking was indeed How can I do this with JavaScript and HTML rather than Is there a way I could do this with just HTML and JavaScript?. Basically, I wanted a type of SQL database that would save its contents on the user's machine instead of online.
What solved my problem was using WebDB or WEBSQL (I think it was called something like that that).
I'm about 3 years late in answering this, but considering that there was no actual discussion on the available options at the time, and that the database that OP ended up choosing is now deprecated, I figured i'd throw in my two cents on the matter.
First, one needs to consider whether one actually needs a client-side database. More specifically...
Do you need explicit or implicit relationships between your data items?
How about the ability to query over said items?
Or more than 5 MB in space?
If you answered "no" to all of the above, go with localStorage and save yourself from the headaches that are the WebSQL and IndexedDB APIs. Well, maybe just the latter headache, since the former has, as previously mentioned , been deprecated.
Otherwise, IndexedDB is the only option as far as native client-side databases go, given it is the only one that remains on the W3C standards track.
Check out BakedGoods if you want to utilize any of these facilities, and more, without having to write low-level storage operation code. With it, placing data in the first encountered native database which is supported on a client, for example, is as simple as:
bakedGoods.set({
data: [{key: "key1", value: "val1"}, {key: "key2", value: "val2"}],
storageTypes: ["indexedDB", "webSQL"],
//Will be polyfilled with defaults for equivalent database structures
optionsObj: {conductDisjointly: false},
complete: function(byStorageTypeStoredKeysObj, byStorageTypeErrorObj){}
});
Oh, and for the sake of complete transparency, BakedGoods is maintained by this guy right here :) .

Categories

Resources