Passing values from a page to another page in HTML mobile app - javascript

I've made users to enter some values in a html page:
Here is the code:
$(function() {
$("#savesymptoms").bind(
"click",
function() {
var url = "notes.html?acne="
+ encodeURIComponent($("#acne").val())
+ "&back="
+ encodeURIComponent($("#bloat").val());
window.location.href = url;
});
});
And I've added an alert like this:
alert("values passed");
But I'm not sure that this is working. I've got some 10 values to pass to another page. Above code contains only two values. Can I use arrays to pass all 10 values? I don't want to use nomenclature used in my code, i.e., individual value passing.
P.S: acne and bloat are the ids of the fields where user enters the data. notes.html is the page where I want to pass the data.

In my opinion you can use sessionStorage in HTML5
For setting a value
sessionStorage.setItem('name', 'value');
For getting the value:
sessionStorage.getItem('name');
if you want to store the value permanently use localStorage.
Since you have almost 10 values push all those values in a JSON and store it either in sessionStorage/localStorage.
You can retrieve it else where and use as per your wish
Note:values stored will be in the form of string even if you push it as JSON.You will have to make it to JSON using Jquery functions
Alternative
You can store it as window.name
But this will be only valid till the window lasts/tab closed(same as sessionStorage)

Related

Looping through array to store string values in objects in localStorage and retrieving them

I'm building a web app that lets the user curate a double-feature film showing. The user enters a title, a blurb, and two film titles. On a submit button a function is called that displays the user-submitted title, user-submitted blurb, and makes two separate API calls to retrieve movie information on each respective feature.
I'm trying to establish something of a favorites functionality that utilizes localStorage. Conceptualizing the solution, let alone implementing it may be my first mistake, so I'm open to alternative suggestions, but I believe the best way to do this is to capture each search field value (title, blurb, movie_1, movie_2), store these four string values in an object and then push that object to an array, placing each object into localStorage and then getting each object from localStorage later on with a button click.
I'm able to capture these items, store them in localStorage and dynamically generate buttons that when clicked populates the four search field values back into the respective search fields, allowing the user to click the submit button again which runs the api calls and displays all of the content (again: title, blurb, movie_1, movie_2).
My problem is looping through the objects and grabbing the different search field data values. I suppose the problem is in assigning a name or key to the different objects that I'm looping through in the array and then accessing the correct values from the appropriate button through localStorage. I seem to be setting the same localStorage object (or rewriting it) and accessing it over and over, as opposed to setting a new localStorage object and getItem'ing the right one.
I'll provide some code snippets below, but it might be easier to peruse my GitHub repo: https://github.com/mchellagnarls/double_feature
If you look at the repo, latest code is found in index_test.html and app_test.js, whereas a previous version without any of the broken favorite functionality is found in index.html and app.js.
Some code snippets:
// logic to capture search field values and to eventually display them as buttons
// empty array
var dfArray = [];
// object to hold each of the string values to populate the search fields
var doubleFeature = {
feature_1: movie_1,
feature_2: movie_2,
DFTitle: title,
DFBlurb: blurb
}
dfArray.push(doubleFeature);
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var savedDF = JSON.parse(localStorage.getItem("df"));
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})
Thanks for any help. I'm learning web development and I may be overcomplicating things or missing out on an easier way to think about it and/or solve it.
Instead of this loop:
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
I would place the whole array into local storage
localStorage.setItem("df", JSON.stringify(dfArray));
Also then you have to decide which object to get from array in click function
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var id = -1; // which one
var savedDF = (JSON.parse(localStorage.getItem("df")) || []).find(pr => pr.id === id);
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})

how to send variable value from one page to another

I am trying to send an information from one page to another through javascript file
the information will only contain a value of single variable.
how to accomplish this?I dont want to send it through query string as the value will be visible in the URL.
is there any other way?
You could save your data in LocalStorage and retrieve it on the other page.
localStorage.yourData = '{ test:"data" }';
console.log(localStorage['yourData']);
You have a few options to do that.
Depending on what browser is used, using localStorage is an option
//localStorage ONLY stores flat key:value pairs and can't contain Objects
localStorage.myString = "hello world";
localStorage.myObject = JSON.stringify({ foo: "bar" });
//Reading back the values is simple aswell
var myString = localStorage.myString;
var myObject = JSON.parse(localStorage.myObject);
Another method would be using a hash or query string. For example, you could redirect to www.yourdomain.com/your/path?myValue=1234
And then parse that by reading the search value from window.location.search (Will return ?myValue=1234 in that case) and splitting it on =:
var myValue = window.location.search.split("=")[1];
Another option is using hashes, similar to query params. Or even cookies.
BUT, all these methods will expose the value to the user, so if he wants to get that value, he will be able to!
At first, as other answers, use localStorage or sessionStorage to store global data.
Otherwise, you can add an event listener to detect the change of the storage value in your target page as follow:
window.addEventListener('storage', (e) => console.log(e.key, e.oldValue, e.newValue))
See: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent

Storing multiple ID's in localStorage using JavaScript

I am wanting to add a favorites function for my website. The technologies I am using are html, css, javascript and json. I am loading the json file thru ajax. A user is able to search for a device and add that device to their favourites and that is done via sessionStorage and localStorage, but my problem is when a user clicks on a new phone to add to their favorite, it overrides it. Do I have to put like an IF statement which will say if there is an id there still add this one. I am confused on how to do this...
Code Samples....
$(document).on('click', '.productfavourite', function(event) {
// whichever HTML element has been clicked,
// grab the id of that and set it as product fave
productFave = event.target.id;
localStorage.setItem('productFave', productFave);
console.log(productFave);
window.location="favourites.html";
});
I would suggest you save the selected items in an object or array before you write it in to the localStorage. After that you convert the object or array to a json string.
var selected = [];
$(document).on('click', '.productfavourite', function(event) {
selected.push(event.target.id);
console.log(selected);
});
this returns an array that your can convert to json.
Hope this helps.
So what you need is to keep a collection (list or dictionary) containing the favorites. I'll give you some examples, then you can figure out the rest.
You get the current productFav in your localStorage as follows:
var fav = localStorage.getItem("productFav") || [];
Now you don't want to store one value in localStorage, you want your whole list there. So you add the new favorites to the list and serialize the result as a json string
fav.push(newItem);
localstorage.setitem("productfav", JSON.stringify(fav));
I assumed fav is a list. It's best to use a dictionary if you want to avoid adding duplicated entries
You can also try:
if(Storage !== "undefined") {
localStorage.setItem("productFave", localStorage.getItem("productFave")+ ", newItemValue3");
}

pass multidimensional javascript array to another page

I have a multidimensional array that is something like this
[0]string
[1]-->[0]string,[1]string,[2]string
[2]string
[3]string
[4]-->[0]string,[1]string,[2]string[3]string,[4]string,[5]INFO
(I hope that makes sense)
where [1] and [4] are themselves arrays which I could access INFO like myArray[4][5].
The length of the nested arrays ([1] and [4]) can varry.
I use this method to store, calculate, and distribute data across a pretty complicated form.
Not all the data thats storred in the array makes it to an input field so its not all sent to the next page when the form's post method is called.
I would like to access the array the same way on the next page as I do on the first.
Thoughts:
Method 1:
I figure I could load all the data into hidden fields, post everything, then get those values on the second page and load themm all back into an array but that would require over a hundred hidden fields.
Method 2:
I suppose I could also use .join() to concatenate the whole array into one string, load that into one input, post it , and use .split(",") to break it back up. But If I do that im not sure how to handel the multidimensional asspect of it so that I still would be able to access INFO like myArray[4][5] on page 2.
I will be accessing the arrary with Javascript, the values that DO make it to inputs on page 1 will be accessed using php on page 2.
My question is is there a better way to acomplish what I need or how can I set up the Method 2 metioned above?
This solved my problem:
var str = JSON.stringify(fullInfoArray);
sessionStorage.fullInfoArray = str;
var newArr = JSON.parse(sessionStorage.fullInfoArray);
alert(newArr[0][2][1]);
If possible, you can use sessionStorage to store the string representation of your objects using JSON.stringify():
// store value
sessionStorage.setItem('myvalue', JSON.stringify(myObject));
// retrieve value
var myObject = JSON.parse(sessionStorage.getItem('myvalue'));
Note that sessionStorage has an upper limit to how much can be stored; I believe it's about 2.5MB, so you shouldn't hit it easily.
Keep the data in your PHP Session and whenever you submit forms update the data in session.
Every page you generate can be generated using this data.
OR
If uou are using a modern browser, make use of HTML5 localStorage.
OR
You can do continue with what you are doing :)

Place string on page

I am using window.opener to pass a string value from a child window to a parent window as so-
function reply_click(clicked_id)
{
alert(clicked_id);
window.opener.document.write(clicked_id);
window.close ();
}
Where the cliced_id is the string I am passing back.
However I want to pass this back to a hidden input on the main page so I can use it again. The problem being is that I cannot specify where to put the string value on the main page and instead it just loads the string value in a new page without any of the original content.
Is it possible to pass back the string and keep the original HTML content?
Yes, if you have a an element on the original page with an id , you can reference that using getElementById and set the innerHTML:
eg, with an empty div on the page:
<div id="myDiv"></div>
You could use this code
function reply_click(clicked_id)
{
alert(clicked_id);
window.opener.document.getElementById("myDiv").innerHTML = clicked_id;
}
Yes, window.opener is a complete window reference.
You could call window.opener.myCallback(clicked_id) or window.opener.clickedId = clicked_id
hi why dont you store your values in html5 storage objects such as sessionStorage/localStorage, visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values
for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects

Categories

Resources