Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap - Pass JS data between the pages

I have a question about passing data between the pages from one JQM / Phonegap App.

If I have an JS object with some data like: search term, location and some other filter values and for example the user is jumping from the search page to the settings page and goes back for example again to the search page ... how can I save the information, what I had in the previews page? Is there something like cookies or should I ever use the sqlite to save the information and read it every time the user is coming to the search page?

like image 657
Mutatos Avatar asked Feb 01 '13 13:02

Mutatos


Video Answer


2 Answers

I would use LocalStorage, is quite simple to use. It allows you to store plain text:

// Writing 'something' in localStorage.myvariable
localStorage.myvariable = 'something'

// Displaying the previous variable
console.log(localStorage.myvariable)

If plain text is not enough and you need to store data structures, you could implement something like:

Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }
Storage.prototype.getObject = function(key) { var value = this.getItem(key);return value && JSON.parse(value); }

// Storing a JSON object
localStorage.setObject('myObject', {key1: 'value', key2: 'value2'});

// Accessing the object
localStorage.getObject('myObject')
like image 123
davids Avatar answered Oct 12 '22 23:10

davids


I've used this hashtag approach (2014 now), as I have only 1 or 2 items to pass. You can pass it via # tag and then split the results with JS into and array... for example:

From URL: index.html#var1?var2

Resolved Page:

var str = str.window.location.hash.substr(1);
var res = str.split("?");
alert(res[0]+","+res[1]);

Hope that helps someone. LocalStorage and the other options are just too heavy for this type of lifting IMO.

like image 36
jasonflaherty Avatar answered Oct 13 '22 00:10

jasonflaherty