Making a simple task tracking application, I've just implemented local storage to the app and am struggling to output the stored information. The information that is stored is correct when I check in the chrome console.
The code below is how I store the data and how I currently outputted the inputted data from the user.
var taskItem = "<div class='task-item'><h1 class='task-name'>" + name + "
</h1><h1 class='task-date'>" + date + "</h1><h1 class='task-assigned'>" +
assigned + "</h1></div>"; //Current output of inputted data from user
localStorage.setItem("Lname", JSON.stringify(name)); //storing the
//inputted data
localStorage.setItem("Ldate", JSON.stringify(date));
localStorage.setItem("Lassigned", JSON.stringify(assigned));
$(".task-wrapper").prepend(taskItem)
What I'm trying to do now is output the local storage on the next boot up of the app. Any pointers would be really quite helpful, thank you.
You should be able to do
localStorage.getItem("Lname");
to retrieve your data.
See https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
In my applications I use this little program!
Try it ..
var DB = function(){
this.Read = function(index){
return JSON.parse(localStorage[index]).data;
};
this.Write = function(index, data){
localStorage[index] = JSON.stringify({data : data});
};
this.Test = function(){ // test support localStorage!
return typeof localStorage == typeof {};
};
this.Clear = function(index){
if(typeof index === "undefined"){
localStorage = {};
} else {
localStorage[index] = JSON.stringify({data : []});
}
};
}
example:
var x = new DB(); // new data base
if(!x.Test()) alert('Error!'); // not support!
x.Write('food', ['food','bar','google']); // write data
console.log(x.Read('food')); // get data!
x.Clear('food'); // clear data!
console.log(x.Read('food')); // get data!
I've got it working now, thank you all for helping!
I had to use to get the data from the local storage.
Rname = $.parseJSON(localStorage.getItem('Lname'))
Thanks.
Related
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.
I need to print in console value of key temp but no things displayed
var database=firebase.database();
var ratingRef = firebase.database().ref("sensors/temp/");
ratingRef.orderByValue().on("value", function(data) {
data.forEach(function(data) {
console.log( data.val());
});
});
There's no need for using orderByValue. You have direct reference to the temp child so the data (which is a DataSnapshot) contain the value of temp only.
var ratingRef = firebase.database().ref("sensors/temp");
ratingRef.on("value", function(data) {
console.log(`Temp: ${data.val()}`)
});
I am trying to save chat message on localStorage (or sessionStorage) and display on web page, I can found the key-value pair stored in Devtool -> application -> localStorage, the message value update everytime when user sends the message and display on web page. However the content gone everytime when page reload. How to solve this?
Also what I am encountering is the push() to save messages to array will replaces instead of adds value, not sure if these 2 issues are related. Thanks.
pug file
#test2(style='height:200px; width:200px; border:1px solid #ccc')
js file
$('#sendMessage').on('click', function() {
var msg = $('#message').val()
var messages = [];
console.log(typeof(messages)); //obj
messages.push(msg);
console.log(messages); //array value
if (localStorage) {
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
localStorage.setItem('username', $('#username').val());
localStorage.setItem('date', currentTime());
var cUser = localStorage.getItem('username');
var cMsg = localStorage.getItem('message');
var cTime = localStorage.getItem('date');
} else {
console.log('localStorage is not supported.');
}
document.getElementById("test2").innerHTML += "<div>" + cUser + " : " + cMsg + "</div>";
// Clear the field
$('#message').val('');
}); // End click
reload page lose data
// Send Message
$('#sendMessage').on('click', function() {
// get value
var username = $('#username').val();
var msg = $('#message').val();
var time = currentTime();
//check if localStorage works and create msgArray
if (!localStorage) {
console.log('localStorage is not supported.');
} else {
//check if there is existing message array in msgArray
var msgArray = localStorage.getItem('message');
//if there is NULL, setup msgArray = [], converts a JavaScript value to a JSON string
if (JSON.stringify(msgArray) == 'null') {
msgArray = [];
} else {
//else parses a JSON string, constructing the JavaScript value or object described by the string
msgArray = JSON.parse(msgArray);
}
}
//add new message object to msgArray
var newMsg = {
msg: msg,
username: username,
time: time
};
msgArray.push(newMsg);
// stringsfy the message and store it to localStorage
localStorage.setItem('message', JSON.stringify(msgArray));
// dispaly current messages
var cMsg = JSON.parse(localStorage.getItem('message'));
// console.log(cMsg); // should shows list of array with new added message objects
// for (var i = 0, max = cMsg.length; i < max; i++) {
//document.getElementById("test2").innerHTML += "<div>" + cMsg[i].username + " : " + cMsg[i].msg + " at " + cMsg[i].time + " </div>";
$('#test2').append('<div class="well well-sm">' + cMsg[cMsg.length - 1].username + ' : ' + cMsg[cMsg.length - 1].msg + ' <span class="pull-right"><small id="date"> at ' + cMsg[cMsg.length - 1].time + '</small></span></div>');
// load the bottom of message
var objDiv = document.getElementById("chatArea");
objDiv.scrollTop = objDiv.scrollHeight;
// Clear the field
$('#message').val('');
}); // End click
I am not sure what you are trying to accomplish with your for loop, since you seem to be setting the same value as many times as you have messages (essentially that's worth nothing, setting it once should be enough)
Let's revisit your steps:
You are getting a value from an input element with id message, and saving it into the msg variable
var msg = $('#message').val()
You construct a new array, and push it in
var messages = [];
messages.push(msg);
And then you iterate the array, but re-use the msg variable
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
So essentially, you did this:
localStorage.setItem('message', $('#message').val());
and nothing more. Maybe you wanted to get the array of messages first, and then add the new message to it, rather something like the following
function addMessage() {
// get the potential array
var messages = JSON.parse( localStorage.getItem('message') || '[]' );
// add the message
messages.push($('#message').val());
// save the array as a string, using JSON.stringify
localStorage.setItem('message', JSON.stringify( messages));
// empty the message value
$('#message').val('');
console.log(messages);
}
If you want to save some chat messages, I think you should make sure that all message are properly linked with the author's username and the time it was wrote.
You tried an array... For the messages, but not for the other infos.
And you misused the array.
LocalStorage will only store a string.
Well... I think it can store objects too... But It is a habit of mine to always store strings.
This way, it always can be console logged fast, instead of bugging...
So stringify the array before saving it.
And when you retreive it,you have to parse it back to an array to be able to push a new message into it.
Ok... So will you try to synchronize 3 or more arrays?
I suggest ONE array of objects.
Each objects containing all the relevant infos linked to a particular message.
See comments in code.
$('#sendMessage').on('click', function() {
// ...
var chatWindow = $("#chatWindow");
// Get all values now.
var msg = $('#message').val();
var username = $('#username').val();
var time = moment().format("hh:mm:ss");
if (!localStorage) {
console.log('localStorage is not supported.');
}else{
// Retreive previous messages
var messageArray = localStorage.getItem('message');
// If there was none, set it as an array
if(JSON.stringify(messageArray) == "null"){
console.log(JSON.stringify(messageArray));
messageArray = [];
// If there was, get them back from string to an array of objects.
}else{
messageArray = JSON.parse(messageArray);
}
// Set the new message object.
var newMsg = {msg:msg,
time:time,
username:username
}
// Insert the new message object in the array.
messageArray.push(newMsg);
// Save the array as a string.
var messagesStringified = JSON.stringify(messageArray);
localStorage.setItem('message', messagesStringified);
// I suppose that showing the messages from what is saved re-assures you about the saving...
var cMsg = localStorage.getItem('message');
// Empty chatWindow
chatWindow.empty();
// Loop through the messages.
var allMessages = JSON.parse(cMsg);
for(i=0;i<allMessages.length;i++){
chatWindow.append("<div>" +
allMessages[i].time +
" | "+ allMessages[i].username +
" : " + allMessages[i].msg + "</div>");
}
console.log(JSON.stringify(messageArray));
// Clear the field
$('#message').val('');
}
}); // End click
$('#clear').on('click', function() {
localStorage.clear();
});
Have a look on **CodePen.
I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}
Is it possible to use a non static variable with chrome.storage.local.get. Right now, I can not recover anything.
here's what I do:
myVar = 'test';
var obj = {};
obj[myVar] = Output;
storage.set(obj);
and to recover, I do:
var key = example + 'js';
storage.get(key, function (result) {
console.log (result.key)
});
Thank you in advance for your help!
You can pass null as the query to retrieve the whole storage:
chrome.storage.local.get(null, function(data) {
// data contains everything in storage
});