Keep array data on page load - javascript

I am trying to keep values in my array on different pages (Wordpress), I'm trying do this via global array but it doesn't seem to work. On "page-1" I am filling the array with data, the same script is loading when I click "page-2". I would be grateful if you point how to fix my problem.
var myArray = new Array();
// Here is issue my myArray with data becomes empty after second load
myArray = {
tablica: []
};
jQuery(document).ready(function(){
// need my array over here
});

It will again reinitialize on next page. You can use local storage for get value from first page to another page.

Unless your app is a spa, a new html page is loaded on navigation. Therefore your JS is re initialise. Global variable does not persist on navigation.
Use local storage, session storage or a server side solution.

Related

How do you save an array to session storage?

I've read a few similar threads, but the solutions are not working for me. The page I am working on has filters for a gallery of images. Each time I click on a filter the images with reload according to that filter via a JSON file.
If I want to apply multiple filters I would need the ones chosen prior to the reload to save in an array variable.
This is the code I have for this
let filterArray = []
sessionStorage.setItem('filterArray', JSON.stringify(filterArray))
let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))
Right now I don't have the page reload set up but after clicking on a filter and refreshing the page I would expect to be able to log the 'savedArr' variable but when I do I get this:
Uncaught ReferenceError: savedArr is not defined
at :1:13
You can't log savedArr after you refresh the page, you need to redefine it.
The data in session storage will persist, but your variable declarations will not.
Call the declaration line again after you reload the page and you will have access to the data.
let savedArr = JSON.parse(sessionStorage.getItem('filterArray'))

i am not able to load array from session storage in java script

I am not able to restore a created array in html and reuse it again.
I have used Json but do not work with me.
in the below code. I'm trying to reload items which is an array created in another page. when i try to load it, it did not work. how can i fix this?
does json need header file?
Thank you.
$( document ).ready(function() {
var count=sessionStorage.getItem('items');
)};
The sessionStorageproperty allows you to access a session Storage object for the current origin.It is two way process first of all stringifyobject before storing to session and second parseto getting back .
var user = {'name':'John'};
sessionStorage['user'] = JSON.stringify(user);
console.log(sessionStorage['user']);
var obj = JSON.parse(sessionStorage['user']);
console.log(Object.keys(obj).length);
Here is fiddle.Opening a page in a new tab or window will cause a new session to be initiated.
More About session storage.
You have to convert your array to a string before setting and back again when your get the item
var letters = ['a', 'b', 'c'];
sessionStorage.setItem("letters", JSON.stringify(letters));
var storedLetters = JSON.parse(sessionStorage.getItem("letters"));
console.log(storedLetters);

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

Saving and accessing API results in a variable in Chrome extension

I'm making a Chrome extension that pulls a large amount of data from an API and uses it to modify content on a page. Because the amount of data is so large, I'd like to be able to save it once in the browser and be able to access it instead of doing an API call each time a page loads.
It's my understanding this can be done by putting the API call in the background page and then calling the variable from the background page in the content script. I've also tried storing the data in local storage. Neither method is working for me and I don't understand what I'm doing wrong.
In my code in the background page, I have the API results stored in a variable. I'm calling it in the content script like this:
var background = chrome.extension.getBackgroundPage();
var myData = background.APIData; //where APIData is the variable I set in the background page
My attempt to use local storage looks like this:
//Background page
chrome.storage.sync.set({'value': APIData}, function() {
// Notify that we saved.
console.log('APIData saved to storage');
});
//Content script
var myData = localStorage["APIData"];
As of this moment, the extension isn't even loading in the page using the code where I'm trying to access local storage. The extension will load with the other method but the data doesn't seem to be there. I know my API call is working because the extension works when I put it all in the content script. But that creates the problem where I'm calling the API each time the page loads. Help please!
Examine your code closely. You are setting the data to two different bins.
First, you call chrome.storage.sync.set and set "value" to the value of APIData.
Second, you call localStorage['APIData'] which refers to a separate storage bin and property name.
Two solutions here, the first being the preferred way to set/get persistent data in a Chrome extension:
A1) set it with chrome.storage.sync.set( { value:data } )
A2) get it with chrome.storage.sync.get( null, function( storage ){ storage.value } )
B1) set it with localStorage.value = data
B2) get it with localStorage.value

How to have a constant value for a variable across many html pages using javascript?

I have a website with two web pages. In page1 when a button gets clicked it loads page2 and in page2 when a button gets clicked it loads page1.
The problem is i have a variable var c=0 in .js file that increases by 1 when page two loads and doesn't stay 1 when page1 loads rather it becomes 0 again.
Is there a way by which when var c increases to 1 it stays 1 over all pages till i change it again ?
Pass the value in url's query string and fetch in other page increase it and set to query string again for next request.
page2.jsp?c=0
In short: You can't store it as a regular variable if the page is reloading.
You might be able to get away with a single-page app framework like AngularJS, but that's really not worth re-archetecting your codebase for.
Instead, try putting your data in localStorage. You can only store strings there, but most things that aren't functions store well with JSON.stringify.
For example:
page1.js
var myVar = 'hello';
localStorage.setItem('myVar',myVar);
page2.js
var myVar = localStorage.getItem('myVar');
console.log(myVar); // Logs 'hello'
These are the few options available:
Cookies: Click here
Local Storage : here or here
JSON data: here
Or add them into your database/webserver.
It all comes down to you and your project..
Good luck with your project!

Categories

Resources