javascript, html onclick change variable - javascript

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.

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?

I need access to variables both in php and the page's javascript

I am working on a php/JavaScript web application that must perform many calculations using many values input by the user. There are several pages of inputs, and calculations using values input on previous pages are everywhere.
I have been passing the recently entered values between pages using $_POST, and storing them for use in a serialized class saved as a $_SESSION variable. One obvious way to pass values from PHP to the page for use by JavaScript is to populate the page with hidden form elements. JavaScript could use this data and modify it as necessary, then pass the values via POST.
I may have many such hidden elements, and I can't help but think that this is a good way to slow down the pages. Is there a better way to store this data between pages? Cookies?
Thanks!
SH
Search AJAX in google. It's a technic that helps your javascript to communicate with your php. First it is hard to learn the syntax but watching videos from youtube will do just fine.

introduce a draft like functionality using javascript

I have a stand alone HTML form, and I want to add a functionality similar to a save as draft. If suppose the user fills up half form and decides to pause and continue filling form some time later . When the user visits the website again the previously filled data should be available to the user. In simple words I want to achieve something like save and complete the form later.
Also to add this is a stand alone HTML form using javascript. When I browsed on the net one suggestion I found was localStorage. But just want to know if there is some other way of achieving this functionality. Please direct me to some useful link which can help me with this feature.
If you act on the client you may use all the clientside persistent facilities currently available like local storage, websql, cookies.
I think that local storage is the easier to implement and you find a lot of libraries that provide you a friendly interface to interact with it like http://www.jstorage.info/ for jQuery or https://github.com/tymondesigns/angular-locker for AngularJS.
What you need to do is something like:
var frm = $(document.myform);
var inputs = frm.find('input');
inputs.change(function() {
var data = JSON.stringify(frm.serializeArray());
localStorage.setItem("form", data);
})
You can put a check for the existence of that key in local storage during the page load and then populate the form accordingly.
Hope it helps :)
There are only a few ways to do this. A completely portable implementation will require server-side changes.
localStorage - Save Form using localstorage HTML5
 Use Javascript to save the data which is entered into the form as it changes. I recommend implementing this layer no matter which version you decide to go with.
Save in database - Examples vary by back-end language.
 The simplest implementation of this is to add a single boolean column to your database which indicates all data necessary to continue has been collected. This version has the benefit of being usable across machines.
Cloud storage - http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-intro.html
 You might consider using a service like Amazon DynamoDB or another NoSQL cloud storage system to cache data like this. The convenience of sending a JSON object to most NoSQL engines and restoring the same to a form is great, and codes very similar to the localStorage version.
Q-Code / Code restoration - http://webqr.com/
 This, in my opinion, is the worst option. However, it may fit your scenario. Generate a Q-Code which the user can scan to restore the page with the data. Q-Codes can hold a surprising amount of data. If your form doesn't use much text entry, you might get away with giving the user a short code (5-8 characters) which can be used to restore the form state.

Multiple cookies with javascript, stategies anyone?

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)

Categories

Resources