How to add data locally in many columns? - javascript

someone can help me here ? How do I add data locally in many columns ?
I have tried but...
Below my code,
I tried to create more var like : "var salary = document.forms.MedList.salary.value; var test = document.forms.MedList.test.value;
localStorage.setItem(name, data, salary, test);
" etc, but It does not work...
I have to change my doShowAll function or something like this ?
function SaveItem() {
var name = document.forms.MedList.name.value;
var data = document.forms.MedList.data.value;
localStorage.setItem(name, data);
doShowAll();
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Nome</th><th>Estoque</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
if (list == "<tr><th>Nome</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store Med list as your browser do not support local storage');
}
}

Your best bet is to create an object and store that e.g.
var myObject = {
name: document.forms.MedList.name.value,
data: document.forms.MedList.data.value
}
localStorage.setItem("yourKey", JSON.stringify(myObject));
When you want to grab it out you can do:
var myObject = JSON.parse(localStorage.getItem("yourKey"));
and then access the name and data respectively:
myObject.name
myObject.data
If you wanted to store multiple values under one key, the value can be an array:
e.g.
var myObject = {
name: document.forms.MedList.name.value,
data: document.forms.MedList.data.value
}
var myObject2 = {
name: document.forms.MedList2.name.value,
data: document.forms.MedList2.data.value
}
localStorage.setItem("yourKey", JSON.stringify([myObject, myObject2]));

Related

For loop not iterating a variable

I'm just learning javascript and I'm trying to update woocommerce products through GAS.
The issue in question is the following:
I have a variable that parses the response from woocommerce
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
Then I have another for to iterate and from a new array that contains id + sku of wooProducts and price from a different variable that takes the updated price from my sheet:
var idLength = wooProducts.length;
Logger.log(idLength);
for (var i = 0; i < idLength; i++) {
var container = [];
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
I can't tell exactly why it doesn't work. I mean the for loop works, it pushes id, sku and price in every loop, it's just that data[i] only provides the first ¿object? instead of looping like wooProducts which add +1 at every loop.
I'll copy 3 loops so it's crystal clear, I'm not sure it's already clear.
Loop 1:
[{"id":1622,"sku":"PD-1000-B","price":8145.9}]
Loop 2:
[{"id":1624,"sku":"PD-1007-A","price":8145.9}]
Loop 3:
[{"id":1625,"sku":"PD-1014","price":8145.9}]
As you can see id+sku change but price doesn't.
For further context, I'll include the data variable that is declaed outside the For:
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
//** EDIT:
I'm adding the entire code so it makes more sense maybe?
function getDataloopwoo() {
var ck = 'xxx'
var cs = 'xxx'
var website = 'xxx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
var skuSearch = sheet.getRange("A2:A").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
Logger.log(skuSearch)
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var idLength = wooProducts.length;
Logger.log(idLength);
var container = [];
for (var i = 0; i < idLength; i++) {
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
Logger.log(container);
var wooBatch = JSON.stringify(container);
Logger.log(wooBatch);
}
}
}
// FINAL EDIT with "solve":
So I figured it was inefficient to ask by 1 sku at a time, so now I'm asking by the 100, and paginating with a while if and saving id, sku, price to the container array.
I will need now to compare the container array to the array with the updated prices and form a new array with id, sku and updated price, I'm reading up on that right now. The code:
function getDataloopwoo() {
var ck = 'xx'
var cs = 'xx'
var website = 'xx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
var container = [];
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100";
var url = surl
//Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
var headers = result.getAllHeaders();
var total_pages = headers['x-wp-totalpages'];
var pages_count = 0;
while (pages_count < total_pages) {
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
//Logger.log(result.getContentText());
}
for (var i = 0; i < wooProducts.length; i++) {
//Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: wooProducts[i]["price"],
});
Logger.log(container);
}
pages_count++;
if (pages_count < total_pages){
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100" + "&page=" + (pages_count + 1);
var url = surl
var result = UrlFetchApp.fetch(url, optionsGet);
Logger.log(url);
}
}
}
You're reseting the array container in every iteration of the loop:
for (var i = 0; i < idLength; i++) {
var container = []; // <-----------------here
...
container.push({
...
I think the array should be defined outside the loop:
var container = [];
for (var i = 0; i < idLength; i++) {
...
container.push({
...

Looping round array and concatenating results Javascript

Please see my code below, I am interrogating active directory and retrieving back two fields, "name" and "cn". I want to concatenate these in an array and then assign to my drop down list. i.e. name + ' ' + cn. The code below publishes my results wrongly and is displaying all names and cn as individual results i.e. not concatenated.
Can someone advise me and put me in the right direction?
thanks,
George
try
{
// Get LDAP Context
ctx = LdapServices.getLdapContext();
//Specify the search scope
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
var searchFilter = "(&(objectClass=group))";
//Specify the Base for the search
var searchBase = "ou=Licensed Applications,ou=SCCM Apps,ou=Applications,ou=Groups,dc=XXX,dc=XX,dc=XX";
//initialize counter to total the group members
var totalResults = 0;
//Specify the attributes to return
var returnedAtts=["name", "cn"];
ctls.setReturningAttributes(returnedAtts);
//Search for objects using the filter
var answer = ctx.search(searchBase, searchFilter, ctls);
//Loop through the search results
while (answer.hasMoreElements())
{
var sr = answer.next();
var attrs = sr.getAttributes();
if (attrs != null)
{
try
{
for (var ae = attrs.getAll();ae.hasMore();)
{
var attr = ae.next();
var pos = attr.toString().indexOf(":",0);
var attributeName = attr.toString().substring(0,pos);
var name = "";
var cn = "";
for (var e = attr.getAll();e.hasMore();totalResults++)
{
if(attributeName == "name")
{
name = e.next().replace('SCCM_','');
}
if(attributeName == "cn")
{
cn = e.next();
}
}
listItems.push(name + ' (' + cn + ')');
}
}
catch (e)
{
log("Problem listing items: " + e);
}
}
}
}
catch (e)
{
log("Problem searching directory: " + e);
}
finally
{
// Close LDAP Context
ctx.close();
}
I don't know what javascript library you use to have JNDI like code into, but from the purely LDAP point of view :
An attribute can be multi-valued, so every attributes value are returned in a array, even if single valued (possible exception for the dn), for example :
{
"dn":"cn=user,dc=example,dc=com",
"name":["username"],
"cn":["commonname"]
}
If your library works like JNDI, a way to do it could be :
After the line : var attrs = sr.getAttributes();
if (attrs != null) {
try {
log ("name: " + attrs.get("name").get());
log ("cn: " + attrs.get("cn").get());
} catch (e) {
log ("Problem listing attributes from Global Catalog: " + e);
}
}

How to empty an Array in a Script

I have a script that uses AJAX/PHP/SQL to query data and pushes it into an array with a bunch of IF's statements. The changeData function is called every 6 seconds. The first query I return I have 6 arrays. The second time i send a request, my push array(IsVacant1) is double and went to 12. after a while, I have over 500 arrays going into my .each statement.
How do I 'clear' this every time I make a request so that I am not adding arrays? Any help is most appreciated.
function changeData() {
isPaused = true;
var mydata0 = null;
$.post('php/ProductionChange.php', {
'WC': cc
}, function(data) { // This is Where I use an AJAX call into a php file.
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
if (pa != null) {
for (var i = 0; i <= pa.length - 1; i++) {
var job = pa[i][0];
var shipdate = pa[i][1];
var status = pa[i][2];
var name = pa[i][3];
var EnclLoc = pa[i][13];
var Enclsize = pa[i][14];
var backpan = pa[i][15];
var percentCom = pa[i][16];
var IsVisible = pa[i][17];
var png = pa[i][18];
var WorkC = pa[i][20];
baydata = 'bayData' + i + '';
temp = {
job, shipdate, name, EnclLoc, Enclsize, backpan, percentCom, IsVisible, png, WorkC, status
};
isVacant1.push({
baydata: temp
});
}
} else {
ii = 1;
//alert("There are no more job numbers in this bay location. Thank you. ");
}
$.each(isVacant1, function(key, value) {
var job = value.baydata.job;
var ship = value.baydata.shipdate;
var name = value.baydata.name;
var encl = value.baydata.EnclLoc;
var EnclSize = value.baydata.EnclLoc;
var percentCom = value.baydata.percentCom;
var backpan = value.baydata.backpan;
var PngLogo = value.baydata.png;
var IsVisible = value.baydata.IsVisible;
var WorkC = value.baydata.WorkC;
var status = value.baydata.status;
var p = WorkC;
WorkC = (WorkC < 10) ? ("0" + WorkC) : WorkC;
//// remember if the encl location matches the workcell cell then do stuff based on that....... hint encl image not hiding becase of duplicate 17s
if (((encl == p) || (backpan == p)) && job != 123) {
$('#WC' + p).show();
document.getElementById("bayData" + p).innerHTML = name + ' ' + ship; // Work Cell Name and Ship Date
document.getElementById("bayData" + p + "a").innerHTML = job; // Work cell Job Number
document.getElementById("percentCom" + p).innerHTML = percentCom + '%'; // Work Cell Percent Complete
} else {
$('#WC' + p).hide();
From your question it looks like you want to clear the isVacant1 array.
In your ajax callback just put isVacant1 = []; as the first line. Like this
function(data) { // This is Where I use an AJAX call into a php file.
isVacant1 = [];
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
..................
From your code it's not clear how you are declaring/initializing isVacant1 so i have suggested isVacant1 = [] otherwise you can also use isVacant1.length = 0.
You can also take a look here How do I empty an array in JavaScript?

how to get length of an ajax object

I would like to get the length of the 'obj' object so that I can do a for-loop with it, here is my code:
var oRequest = new XMLHttpRequest();
var sURL = "/Users/files/Documents/time.json";
oRequest.open("GET",sURL,false);
oRequest.send();
var txt = oRequest.responseText;
var obj = eval ("(" + txt + ")");
My goal is that I would like to output everything in this time.json file to the screen.
Here is what my json file looks like:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The object you create does not have have a length. I assume you meant employees length and not the obj length
Like this:
Live Demo
var txt = oRequest.responseText;
// eval("var obj = "+txt); // eval is not recommended but here is how
var obj = JSON.parse(txt); // this is better
var emp = obj?obj.employees:[]; // if we have a useful object, get the employees
window.onload=function() {
var empDiv = document.getElementById("empDiv");
for (var i=0;i<emp.length;i++) {
empDiv.innerHTML+=emp[i].firstName + " "+ emp[i].lastName + '<br/>';
}
}
you don't have to get a length in order to do a for loop on an object, based on your object structure you can get data with the following loop:
for(var key in object) {
var o = object[key];
for(var i = 0; i < o.length; i++) {
var user = o[i];
alert(user.firstName);
}
}

Owner dropdown not filtering Story cardboard

I built a custom cardboard mashup to display all user stories that are in a "committed" iteration and beloning to the current project, or any child project. This much works well. I then added an Owner dropdown box (limited to Team Members only), to filter the stories on the cardboard. The resulting query value appears to be well formatted, yet no stories are displayed. I used an alert to copy the query string and paste it into a custom grid, which returned the expected list of stories.
Below is my code. Any assistance is appreciated.
var rallyDataSource;
var cardboard;
var ownerDropdown;
function refreshCardboard() {
var cardboardConfig = {
types: ["Defect", "HierarchicalRequirement"],
attribute: "ScheduleState",
fetch: "Name,FormattedID,Owner,ObjectID"
};
var query = rally.sdk.util.Query.and(['Iteration.Name != ""', 'Iteration.State = "Committed"']);
if (ownerDropdown) {
var ownerQuery = ownerDropdown.getValue();
if (ownerQuery != 'ALL') {
query = '(' + query + ' AND Owner.Name = "' + ownerQuery + '")';
}
}
cardboardConfig.query = query;
if (!cardboard) {
cardboard = new rally.sdk.ui.CardBoard(cardboardConfig, rallyDataSource);
cardboard.display("cardboardDiv");
} else {
cardboard.refresh(cardboardConfig);
}
}
function buildOwnerDropdown() {
var teamMembersQuery = {
key: "teamMembers",
type: "User",
fetch: "UserName,DisplayName",
query: '(TeamMemberships = /project/__PROJECT_OID__)'
};
rallyDataSource.findAll(teamMembersQuery, function (results) {
var ownerItems = [{ label: "-- ALL --", value: "ALL"}];
rally.forEach(results.teamMembers, function (teamMember) {
ownerItems.push({ label: teamMember.DisplayName, value: teamMember.UserName });
});
ownerItems.sort();
var ownerDropdownConfig = {
showLabel: true,
label: "Owner:",
items: ownerItems
};
ownerDropdown = new rally.sdk.ui.basic.Dropdown(ownerDropdownConfig);
ownerDropdown.display("ownerDropdownDiv");
});
}
function onLoad() {
rallyDataSource = new rally.sdk.data.RallyDataSource(
'__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
buildOwnerDropdown();
refreshCardboard();
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="ownerDropdownDiv"></div>
<input id="refreshButton" type="button" value="Filter" onclick="refreshCardboard()"/>
<div id="cardboardDiv"></div>
</body>
You're really close to the mark - the problem lies here:
var query = rally.sdk.util.Query.and(['Iteration.Name != ""', 'Iteration.State = "Committed"']);
if (ownerDropdown) {
var ownerQuery = ownerDropdown.getValue();
if (ownerQuery != 'ALL') {
query = '(' + query + ' AND Owner.Name = "' + ownerQuery + '")';
}
}
Rally's query syntax requires another nested set of parentheses when adding another AND condition. So when you concatenate on your third condition, you are ending up with a query clause that looks like this:
((Iteration.Name != "") AND (Iteration.State = "Committed")) AND (Owner.Name = "user#company.com")
When it needs to look like this:
(((Iteration.Name != "") AND (Iteration.State = "Committed")) AND (Owner.Name = "user#company.com"))
I slightly modified your refreshCardboard() function's query logic as follows, and your code seems to work now for me.
....
var queryArray = new Array('Iteration.Name != ""', 'Iteration.State = "Committed"');
var query;
var selectedOwner = ownerDropdown.getValue();
if (ownerDropdown) {
if (selectedOwner != 'ALL') {
var ownerClause = 'Owner.Name = "' + selectedOwner + '"';
queryArray.push(ownerClause);
}
}
query = rally.sdk.util.Query.and(queryArray);
cardboardConfig.query = query;
....

Categories

Resources