javascript variable name need a increment - javascript

I found the follow problem, I have that code it is inside a loop.
window.setInterval(function() {
requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getFunc + "/?access_token=" + accessToken;
What I need, the variable deviceID need a increment of variable B example:
requestURL = "https://api.spark.io/v1/devices/" + deviceID[B] + "/" + getFunc + "/?access_token=" + accessToken;
So deviceID[B] that B is 1 or 2 or 3, because I have variables with the name deviceID1, deviceID2, deviceID3.
Can you help me?

It's a bad idea to concatenate a variable name, use an array instead:
var myArr = [deviceID1, deviceID2, deviceID3];
for (var i = 0; i < myArr.length; i++) {
var requestURL = "https://api.spark.io/v1/devices/" + myArr[i] + "/" + getFunc + "/?access_token=" + accessToken;
}
The above is a simple example on how you could use an array.

Related

Javascript object set to another object is undefined

For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}

AWS Signing and Javascript

I need to send HTTP request to AWS with signed request via Javascript. Sadly I cannot use the AWS SDK JS as its either for Node.js or browser, but I need to run it from Rhino JS environment.
seems I am doing something very wrong as I get whatever I do same result - AWS was not able to validate the provided access credentials.
:(
The code I am using is same as the one Amazons is using as example (but in Python). I am using only one external lib so I can use HMCA &SHA.
Any help is much appreciated (and needed as I am struggling for days by now...), so yeah - help!
Thanks is advance!
Cheers,
Joro
gs.include('jshashes');
var method = 'GET';
var service = 'ec2';
var host = 'ec2.amazonaws.com';
var region = 'us-east-1';
var endpoint = 'https://ec2.amazonaws.com';
var access_key = 'ACCESSKEY';
var secret_key = 'SECRET/KEY';
var request_parameters = 'AWSAccessKeyId' + access_key + 'Action=RunInstances&&ImageId=ami-b770fbd8';
function getSignatureKey(key, date, region, service){
var newKey = "AWS4" + key;
var kDate = new Hashes.SHA256().b64_hmac(newKey, date);
var kRegion = new Hashes.SHA256().b64_hmac(kDate, region);
var kService = new Hashes.SHA256().b64_hmac(kRegion, service);
var kSigning = new Hashes.SHA256().b64_hmac(kService, "aws4_request");
return kSigning;
}
var gdt = new GlideDateTime();
var datestamp = gdt.getDate().getByFormat('yyyyMMdd') + 'T' +
gdt.getTime().getByFormat('HHmmss') + 'Z';
var amzdate = gdt.getDate().getByFormat('yyyyMMdd')+"";
var canonical_uri = '/';
var canonical_querystring = request_parameters;
var canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
var signed_headers = 'host;x-amz-date';
var payload_hash = new Hashes.SHA256().hex("");
var canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash;
var algorithm = 'AWS4-HMAC-SHA256';
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
var signing_key = getSignatureKey(secret_key, datestamp, region, service);
//Python
//var signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
var signature = new Hashes.SHA256().hex_hmac(signing_key, string_to_sign);
var authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
var headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}
var request_url = endpoint + '?' + canonical_querystring
var httpRequest = new GlideHTTPRequest(request_url);
httpRequest.setRequestHeader(headers);
var res = httpRequest.get();
gs.print(res.statusCode);
gs.print(res.allHeaders);
gs.print(res.body);
Check the URL construction. For one, the request_parameters have some missing and misplaced delimiters.
var request_parameters = 'AWSAccessKeyId=' + access_key +
'&Action=RunInstances&ImageId=ami-b770fbd8';
In addition to inspecting and testing the resulting URL, you might also try to simply the syntax to make it easier to check and update. Just as an example, the following
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
could be written as follows (which seems easier to check to me):
var credential_scope = [
datestamp,
region,
service,
'aws4_request'
].join('/');
var string_to_sign = [
algorithm,
amzdate,
credential_scope,
new Hashes.SHA256().hex(canonical_request)
].join('\n');

How to concatenate strings without using eval?

How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.
function getLesson() {
var lesson = "lesson" + localStorage.lessonNGS;
document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
document.getElementById("lessonScore").src = (eval(lesson + "." + score));
document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
document.getElementById("lessonTrack").load();
}
This works but I'm told it will cause me conflicts in some browsers.
Simply remove the eval
// Demo data
localStorage.setItem("lessonNGS",1);
var lesson1 = {
number: "1",
title: "Quarter Notes",
score: "scores/01_quarternotes.jpg",
trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};
function getLesson() {
debugger;
var lesson = window["lesson" + localStorage.lessonNGS];
document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
document.getElementById("lessonTitle").innerHTML = lesson.title;
document.getElementById("lessonScore").src = lesson.score;
document.getElementById("mp3").src = lesson.trackmp3;
document.getElementById("ogg").src = lesson.trackogg;
document.getElementById("lessonTrack").load();
}
Javascript String.prototype.concat():
str.concat(string2, string3[, ..., stringN])
Example:
var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));

"error CS1012: Too many characters in character literal"

i have a JavaScript code of photo gallery with a slider but there's a problem :
var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";
// check if the file is exiset -- it's running in bar() function -- run on servers and local host.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
return http.status != 404;
}
// push images paths to array
function bar() {
var exict = 0;
var counter = 0; //counter of array's index
for (var i = 1 ; exict < 30; i++) {
// if there isn't .jpg or .gif
if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
exict = exict + 1;
}
// if there is .jpg
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
counter = counter + 1;
}
// if there is .gif
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
gifIndex.push(i);
counter = counter + 1;
}
}
}
but it was not work, so i tried to change var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;
but I got error: "error CS1012: Too many characters in character literal". I'm still not sure that this is the issue, as my original code does work (you can see the initial product image loaded when you visit the site .baumhaus and click on a product range and then any product, you will see the action - before it disappears once it tries to render the thumbnails).
How about
var partnum = '<%= Request.QueryString["partno"] %>'";

concatenating strings in .each loop

This may be a dumb question but I can't seem to get it or find it anywhere.
I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).
Here is my code:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
So that returns each data_str on a separate line but I need it to return it like this:
144:2~145:3~146:4~147:4~148:5 (so on)
Any help would be appreciated, thanks!
Use map and join :
jQuery('#updateAllContentButton').click(function() {
console.log(jQuery('.CommentaryItem').map(function(i) {
return GetID(jQuery(this)) + ':' + (i+1);
}).get().join('~'));
});
Note that you don't have to count yourself : Most jQuery iteration functions do it for you.
You can use an array for that. Like this...
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var arr = [];
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
arr.push(data_str);
//console.log(data_str);
count++;
});
console.log(arr.join());
});
try this:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var data_str = "";
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
change
var data_str = (id + ':' + count + '~');
to
data_str+ = (id + ':' + count + '~');
full code
jQuery('#updateAllContentButton').click(function() {
var count = 1,
data_str;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});

Categories

Resources