Show all objects present in localStorage on a webpage - javascript

I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.

You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}

You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})

Related

Passing javascript object containing another array of objects to localStorage and then to java servlet using ajax

I am trying to work out how to store a javascript object in local storage that has a few items as well as an array of objects, if that is possible. To then extract the data from the local storage and send to a java servlet using ajax, then extract the data from the java HttpServletRequest. Here is some of the code I have written. It's a bit too complex to put the entire code base here. I have multiple forms which a user completes and as they move between forms I store the data entered into local storage.
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
if (formIsValid) {
scenarioObject.SUPER_BALANCE = 420000;
scenarioObject.SUPER_INVESTMENT_FEES = 0.14;
scenarioObject.SUPER_ADMIN_FEES = 120;
scenarioObject.LIFE_INSURANCE = 200000;
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = 1500;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
To extract the data from local storage I do the following:
const object = localStorage.getItem(activeScenario);
const jsonString = JSON.parse(object);
const yourSuperBalance = jsonString.SUPER_BALANCE;
$("#your-super-balance").val(yourSuperBalance);
const yourInvestmentFees = jsonString.SUPER_INVESTMENT_FEES;
$("#super-investment-fees").val(yourInvestmentFees);
const yourSuperAdminFees = jsonString.SUPER_ADMIN_FEES;
$("#super-admin-fees").val(yourSuperAdminFees);
const yourInsurance = jsonString.LIFE_INSURANCE;
$("#life-insurance").val(yourInsurance);
const yourAnnualSuperContribution = jsonString.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
$("#your-annual-lump-sum-super-contribution").val(yourAnnualSuperContribution);
This all works fine, but now I wanted to add an array of objects from a table. I could not figure out a way to add this so I ended up storing two items in local storage. One for all the form data and one for the table data. I didn't like this approach but couldn't get it to work otherwise. Here is how I did the table:
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return JSON.stringify(yourSuperContributionsTableData);
}
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
localStorage.setItem(scenarioName+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION, superContributionsTableDataString);
This all worked but then I had to figure out how to send this data to the server using ajax. Without the table, everything was working fine as follows:
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
I modified this function as follows to add the table data and everything in the java servlet code went wrong.
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
// superannuation table
const superTable = activeScenario+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
// this is already stringified
const superTableItem = localStorage.getItem(superTable);
const superTableData = '&' + ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION + "=" + superTableItem;
const formData = passedData + superTableData;
console.log("formData " + formData);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData + superTableData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
// TODO display messages
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
Can anyone advise how best to store a javascript object in local storage that has an item inside the object which is an array of objects for a table? How do I store this in local storage, retrieve it from local storage, send it to the java servlet using ajax and then retrieve it from the HttpServletRequest. Any assistance would be much appreciated.
I worked out a way to do this. I shall fully explain the situation and then my solution to the problem. Not sure if this is the best solution but it does work.
The situation is that I have multiple forms where the user enters data for calculations, including a table of data. I wanted to store this data on local storage for later retrieval next time the user uses the website. The calculations are done in Java on the server so when the user clicks on something like "calculate" the data in local storage is then sent to the server to perform the calculations and the result is sent back.
I needed to store a javascript object containing some elements plus a table, so basically a javascript object with an array inside it.
Collect data from the table
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return yourSuperContributionsTableData;
}
Where I went wrong with this originally was I stringified the array. As the entire javascript object is going to be stringified this was unnecessary.
Create javascript object and store in local storage
The first step is to extract the item from local storage to update it with the new data from the user. Notice we must parse the object because it was originally stringified.
Secondly set the user entered data on the javascript object. You will notice the call to the function above that retrieves the table data. That table data is set as a key value pair in the javascript object.
const scenarioName = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
isValid = validateYourSuperannuationForm();
if (isValid) {
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
scenarioObject.SUPER_BALANCE = $("#your-super-balance").val();
scenarioObject.SUPER_INVESTMENT_FEES = $("#super-investment-fees").val();
scenarioObject.SUPER_ADMIN_FEES = $("#super-admin-fees").val();
scenarioObject.LIFE_INSURANCE = $("#life-insurance").val();
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = $("#your-annual-lump-sum-super-contribution").val();
scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA = superContributionsTableDataString;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
Send item in local storage to server
I discovered trying to stringify the entire javascript object caused problems at the server. What I had to do was create a new object for the formData to be sent to the server, BUT I had to stringify only the table data, not the entire object. I had to retrieve each item from local storage and set it on the formData object to be passed to the server.
function sendScenarioDetailsToServer() {
const activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const item = localStorage.getItem(activeScenario);
const scenarioObject = JSON.parse(item);
// We must do this because if superContributionsTableData == "" and we then stringify this it will
// end up with a value of """", which will cause an error.
const superContributionsTableData = scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA;
let superContributionsTableDataString = "";
if (superContributionsTableData !== ""){
superContributionsTableDataString = JSON.stringify(superContributionsTableData);
}
const formData = {
SCENARIO_NAME: scenarioObject.SCENARIO_NAME,
DATE_OF_BIRTH: "",
IS_SINGLE: scenarioObject.IS_SINGLE,
IS_RETIRED: scenarioObject.IS_RETIRED,
RETIREMENT_DATE: scenarioObject.RETIREMENT_DATE,
IS_HOMEOWNER: scenarioObject.IS_HOMEOWNER,
FORTNIGHTLY_RENT: scenarioObject.FORTNIGHTLY_RENT,
DATE_RENT_CEASES: scenarioObject.DATE_RENT_CEASES,
IS_SINGLE_AND_SHARING: scenarioObject.IS_SINGLE_AND_SHARING,
SPOUSE_DATE_OF_BIRTH: scenarioObject.SPOUSE_DATE_OF_BIRTH,
IS_SPOUSE_RETIRED: scenarioObject.IS_SPOUSE_RETIRED,
SPOUSE_RETIREMENT_DATE: scenarioObject.SPOUSE_RETIREMENT_DATE,
SUPER_BALANCE: scenarioObject.SUPER_BALANCE,
SUPER_INVESTMENT_FEES: scenarioObject.SUPER_INVESTMENT_FEES,
SUPER_ADMIN_FEES: scenarioObject.SUPER_ADMIN_FEES,
LIFE_INSURANCE: scenarioObject.LIFE_INSURANCE,
ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION: scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION,
EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA: superContributionsTableDataString
}
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: formData,
success: function (data) {
// do stuff here
{
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
In the Java Servlet the data is then extracted from the HttpServletRequest passed to the doPost method. It is retrieved in the usual way by calling HttpServletRequest.getParameter. Converting the table data is a little more complex because it is an array that was converted to a string. I am including an extract of that code in case it is of use to someone.
ArrayList<LumpSumSuperContribution> superContributionsList = new ArrayList<>();
String superContributionsTableData = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
// Array superContributionsArray = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
JSONObject superContributionsMessage = new JSONObject();
boolean errorOccurred = false;
if (superContributionsTableData != null && superContributionsTableData.length() > 0) {
try {
JSONArray superContributionsArray = new JSONArray(superContributionsTableData);
int i = 0;
while (i < superContributionsArray.length()) {
JSONObject contributionObj = (JSONObject) superContributionsArray.get(i);
String ageString = (String) contributionObj.get(SUPER_AGE_CONTRIBUTION);
Validator.WholeNumberResult result6 = Validator.validateMandatoryWholeNumber(ageString, 18, 99,
"Lump Sum Super Contribution age for row " + (i + 1));
if (!result6.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result6.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer age = result6.getNumber();
String contributionAmountString = (String) contributionObj.get(SUPER_AMOUNT_CONTRIBUTION);
Validator.WholeNumberResult result7 = Validator.validateMandatoryWholeNumber(
contributionAmountString, 1, 9999999,
"Lump Sum Super Contribution amount for row " + (i + 1));
if (!result7.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result7.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer amount = result7.getNumber();
String beforeAfterTaxString = (String) contributionObj.get(SUPER_TAXATION_CONTRIBUTION);
Validator.TextResult result8 = Validator.validateMandatoryText(beforeAfterTaxString,
"Lump Sum Super Contribution Before or After Tax for row " + (i + 1), 5, 6);
if (!result8.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result8.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
String beforeAfterTax = result8.getText();
LumpSumSuperContribution superContribution = new LumpSumSuperContribution(age, amount, false,
LumpSumSuperContribution.YOUR_CONTRIBUTION, beforeAfterTax);
superContributionsList.add(superContribution);
i++;
}
if (!errorOccurred) {
scenario.setAllYourSuperContributions(superContributionsList);
// superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, SUCCESS);
} else {
fail = true;
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, FAIL);
messageArray.put(superContributionsMessage);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}else {
scenario.setAllYourSuperContributions(null);
}
}
Summary
Create a javascript array. Then loop through the table data and create a javascript object for each row of the table and push onto the array.
Create or retrieve javascript object stored in local storage. If already in local storage, this object must be parsed using JSON.parse(object).
Set the details on the object entered by the user.
Stringify the javascript array and add the string to the object as a key value pair.
To send the data to the server retrieve the item from local storage and parse the item to extract details from it.
Set the extracted details on a newly created formData object.
Stringify the table data and set as a key value pair in formData.
Using ajax Post the data to the server.
I hope this helps someone in the future. It took me a while of trying different things to find a way to get this to work. If anyone has a better solution please post it.

JS: Textfile to JSON

im a complete beginner to JS and need some help.
I have a Textfile looking like this:
JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
So JOBID, NAME and so on are the Names for the values below.
Now I want to parse it into a JSON object.
I tried to do it like this:
var jdata = new Array();
jdata = data.toString().split('\n');
jsonstring = JSON.stringify(jdata);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
But the result is no JSON object right?
I somehow need to attach connect the parameters to each other so it looks like:
{
"JOBID": 2527,
"NAME": '_DP-2-Q-095-84-1-50.job',
...
}
Somebody can tell me how to convert this correctly or isn't it even possible this way?
Thank you already
You've started correctly but you cannot simply use JSON.stringify(jdata); to convert to JSON. An example in pure JS is like so:
//Load in Input
var input = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None`;
//Split into Lines
var data = input.split("\n");
//Get all the header values
var header = input.split("\n")[0].split(",");
//Init Output Array
var output = [];
//For every row except the first (1...n)
for(var i=1;i<data.length;i++){
//Get all the values
var values = data[i].split(",");
var obj = {};
//For every value in the header
for(var j=0;j<header.length;j++){
//obj[JOBID] = 2527
obj[header[j]] = values[j];
}
//Push to output
output.push(obj);
}
Output now will equal your array of objects. You can then save it as you did before.
// [{"JobID": 2527, "...},{..}...]
jsonstring = JSON.stringify(output);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
You are correct that you need to transform your data before it becomes a proper JSON object.
This is a way to do it (with a bit more modern Javascript):
const data = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
`;
let lines = data.split('\n');
const headers = lines.shift().split(',');
// convert the individual lines to JSON objects
const jsonData = lines.map(line => {
const parts = line.split(',');
// Invalid lines - these are filtered out later
if (parts.length !== headers.length) {
return false;
}
// look up the name of the part from the header and use that as the property name
return parts.reduce((acc, part, index) => ({
...acc,
[headers[index]]: part,
}), {});
}).filter(Boolean); // remove the invalid objects
console.log(jsonData);
Here is a simple approach and you can modify it as for your need
var data = 'JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON\n'
+'2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held\n'+
'2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held\n'+
'2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None';
var spdata = data.split('\n');
//assuming that the first row is always having columns names
var names = spdata[0].split(',');
var mainDataAr=[];
//reading data from the 2nd row
for(var i=1;i<spdata.length;i++)
{
//taking the data from the row at position i
var rdata = spdata[i].split(',');
var obj={};
for(var j=0;j<names.length;j++)
{
obj[names[j]]=rdata[j]
}
mainDataAr.push(obj);
}
console.log(mainDataAr);

data from local storage is not appended and replaced

Objects are being saved into localstorage and I want to retrieve that object and append to the page, also I want to change key name everytime new form is submitted, so at first key = key and then on next form submit I want key = key1 etc.
However I do not know how to achieve that, can someone help me?
var existingData = JSON.parse(localStorage.getItem("key")) || [];
$('body').append(existingData);
$('form').submit(function() {
var newArray = [];
$(".add_id2").each(function(){
newArray.push($(this).val());
});
var newArray2 = [];
$(".add_id").each(function(){
newArray2.push($(this).val());
});
var newData = {
'title': $("#title").val(),
'ingredients': $("#ingredients").val(),
'instructions': $("#inst").val(),
'moreingredients': newArray,
'moreinstruction': newArray2,
'img': img,
};
existingData.push(newData);
localStorage.setItem("key", JSON.stringify(existingData));
You can make the constructor function and call that with the new keyword...Please have a look at this. Hope this will help you.
Example:-
function formData(title, ingredients, instructions, moreingredients, img) {
this.title = title;
this.ingredients = ingredients;
this.instructions = instructions;
this.moreingredients = moreingredients;
this.img = img;
}
var newData = new formData($("#title").val(), $("#ingredients").val(), $("#inst").val(), newArray, newArray2);

how to store more then one data in localstorage

what i need
i need to store more then data in array , such user click on div respective data must be stored in array.
like
id: 1223, city:'chicago',
id:12333,city:' new york';
code
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
step 2.
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
console.log(id);
id = JSON.parse(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
console.log(image_url);
here is snapshot :
i need to store more then string in array.
i have tried by console.log(id.length)//undefined.
i have also looked loop to store more values in localstoarge.
for (var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i))
};
You can stringify entire object and save everything at once:
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
It will also make the code simpler and shorter:
function favaorite(sess_id, name, city, country, event_url, pointer) {
/* store imageurl in localstorage */
var imageUrl = '/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof (localStorage) == 'undefined') {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
// Put the object into storage
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
}
And retrieving saved event data you can simply do reverse:
var eventData = JSON.parse(localStorage.getItem('event'));
Try like this,
U have to create an object and fill the details on every click, push that object into an array and store that array in local storage by using JSON.stringify().
And while retrieving again parse that JSON using JSON.parse().
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData = JSON.parse(localStorage.getItem('eventData '));
if(eventData ==null){
eventData=[];
}
Var details={};
details["sess_id"]=sess_id;
details["name"]=name;
details["city"]=city;
details["country"]=country;
details["event_url"]=event_url;
details["pointer"]=pointer;
eventData.push(details);
localStorage.setItem('eventData', JSON.stringify(eventData));
}
While retrieving parse the string to json u'll get the array of those click event details.
var EventDetails=JSON.parse(localStorage.getItem('eventData '));

Passing Variable from JSON data

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

Categories

Resources