Looping round array and concatenating results Javascript - 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);
}
}

Related

Javascript global variables and references to them and their parts

I'm writing little snippets to learn more about using Javascript with API's, and have stumbled onto another problem I can't figure out on my own. I have a global variable (object?) "coins", read in from the API, and its' data field "symbol". I can use "symbol" to reference the data held there, in part of my code, without any errors. Later in the code, I use it again, and I get an error about it being undefined, despite the fact that the values returned from using it, are both defined, and, what I expected. While we are at it, maybe someone can tell me why I assign values to global variables (declared outside of all of the functions), but the variables when called, are "undefined". To see it in action, visit www.mattox.space/XCR and open up dev tools.
/*
FLOW:
get ALL coins, store NAME and SYMBOL into an object.
loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
hit the API again, with the $NAME added to the URL.
create a table row.
insert data from second API hit, into table row
SOMEWHERE in there, do the USD conversion from BTC.
*/
//var name = getName();
var bitcoinValue = 0;
var coins = new Array;
var form = ""; // Value pulled from the form
var symbol = ""; // "id" on the table
var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol
var formSym = "";
var formUSD = 0;
var formBTC = 0;
var form24h = 0;
function run() {
getFormData();
allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
testGlobal();
}
function testGlobal() {
console.log("These are hopefully the values of the global variables");
console.log(formSym + " testGlobal");
console.log(formUSD + " testGlobal");
console.log(formBTC + " testGlobal");
console.log(form24h + " testGlobal");
}
function getFormData(){ //This function works GREAT!
form = document.getElementById("symbol").value //THIS WORKS
form = form.toUpperCase(); //THIS WORKS
}
function allTheCoins(URL) {
var tickerRequest = new XMLHttpRequest();
tickerRequest.open('GET', URL);
tickerRequest.send();
tickerRequest.onload = function() {
if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
var input = JSON.parse(tickerRequest.responseText);
for(var i in input)
coins.push(input[i]);
testFunction(coins);
}
else {
console.log("We connected to the server, but it returned an error.");
}
console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
}
}
function testFunction(coins) {
for (var i = 0; i < coins.length; i++) {
if (coins[i].symbol == form) { // But right here, I get an error.
formSym = coins[i].name;
formUSD = coins[i].price_usd;
formBTC = coins[i].price_btc;
form24h = coins[i].percent_change_24h;
console.log(formSym + " testFunction");
console.log(formUSD + " testFunction");
console.log(formBTC + " testFunction");
console.log(form24h + " testFunction");
//DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
}
else if (i > coins.length) {
formSym = "Error";
formUSD = 0;
formBTC = 0;
form24h = 0;
}
}
}
/*
if (24h >= 0) {
colorRED
}
else {
colorGreen
}
*/
here is a possible way of doing it that you can get inspired by. its based on a httpRequest promise that set the headers and method.
let allTheCoins = obj => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(obj.method || obj.method, obj.url);
if (obj.headers) {
Object.keys(obj.headers).forEach(key => {
xhr.setRequestHeader(key, obj.headers[key]);
});
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send(obj.body);
});
};
allTheCoins({
url: "https://api.coinmarketcap.com/v1/ticker/",
method: "GET",
headers: {"Accept-Encoding": "gzip"}
})
.then(data => {
ParseCoins(data);
})
.catch(error => {
console.log("We connected to the server, but it returned an error.");
});
function ParseCoins(data) {
const coins = JSON.parse(data);
const form = getFormVal();/*retrieve form val*/
const id = getTableId(); /*retrieve table id*/
const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
const final_result = [];
for (let i = 0, len = coins[0].length; i < len; i++) {
const coin = coins[0][i];
for (let ii in coin) {
if (coin.hasOwnProperty(ii)) {
if (coin[ii].symbol == form) {
let element = {
formSym: coin[ii].name,
formUSD: coin[ii].price_usd,
formBTC: coin[ii].price_btc,
form24h: coin[ii].percent_change_24h
};
final_result.push(element);
}
}
}
}
coontinueElseWhere(final_result);
}

mediawiki api can not display the results from array

Hello you wonderful people, I am trying to build JavaScript file to extract information from Wikipedia based on search value in the input field and then display the results with the title like link so the user can click the link and read about it. So far I am getting the requested information in(JSON)format from Mediawiki(Wikipedia) but I can't get it to display on the page. I think I have an error code after the JavaScript array.
I'm new at JavaScript any help, or hint will be appreciated.
Sorry my script is messy but I am experimenting a lot with it.
Thanks.
var httpRequest = false ;
var wikiReport;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getWiki(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var search = document.getElementsByTagName("input")[0].value;//("search").value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=" + search , true);//("get", "StockCheck.php?t=" + entry, true);
//httpRequest.send();
httpRequest.send();
httpRequest.onreadystatechange = displayData;
}
function displayData() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
wikiReport = JSON.parse(httpRequest.responseText);//for sunchronus request
//wikiReport = httpRequest.responseText;//for asynchronus request and response
//var wikiReport = httpRequest.responseXML;//processing XML data
var info = wikiReport.query;
var articleWiki = document.getElementsByTagName("article")[0];//creating the div array for displaying the results
var articleW = document.getElementById("results")[0];
for(var i = 0; i < info.length; i++)
{
var testDiv = document.createElement("results");
testDiv.append("<p><a href='https://en.wikipedia.org/?curid=" + query.pages[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = info[i].pages;
newA.setAttribute("href", info[i].pages);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = info[i].title;
newP2.className = "url";
newDiv.appendChild(head);
newDiv.appendChild(newP2);
articleWiki.appendChild(newDiv);
}
}
}
//
function createEventListener(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener("submit", getWiki, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", getWiki);
}
}
//createEventListener when the page load
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
Mediawiki api link
https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=
You are wrong some points.
1)
var articleW = document.getElementById("results")[0];
This is wrong. This will return a element is a reference to an Element object, or null if an element with the specified ID is not in the document. Doc is here (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
The correct answer should be :
var articleW = document.getElementById("results");
2)
var info = wikiReport.query;
for(var i = 0; i < info.length; i++) {}
The info is object . it is not array , you can't for-loop to get child value.
wikiReport.query is not correct wiki data. The correct data should be wikiReport.query.pages. And use for-in-loop to get child element
The correct answer:
var pages = wikiReport.query.pages
for(var key in pages) {
var el = pages[key];
}
3) This is incorrect too
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. You are using the method to adds a string . This will cause error. Change it to node element or use append method instead
I have created a sample test.You can check it at this link below https://codepen.io/anon/pen/XRjOQQ?editors=1011

How to add data locally in many columns?

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]));

Perform an async task with a web worker JavaScript

I want to show a loading icon while a task is being performed and then hide the icon after it has been performed. I need to use a web worker for the loading icon to show. The admin at This forum post said to use a web worker.
This is the code to execute in the web worker:
function getTheClients(xml) {
console.log(xml);
var client = xml.getElementsByTagName("WebClientList");
if(client.length === 0) {
$("#noClients" + platform).empty();
$("#noClients" + platform).append('<p style="margin-top:40px;margin-bottom:20px;text-align:center;">No clients at ' +
getSelectedDropDownOptionName("allVillagesDropDown") + ', ' +
getSelectedDropDownOptionName("allLocationsDropDown") + '.</p>');
$("#noClients" + platform).attr("style", "display: block");
$("#theClientsList" + platform).attr("style", "display: none");
} else {
$("#noClients" + platform).attr("style", "display: none");
$("#theClientsList" + platform).attr("style", "display: block");
}
for (i=0; i < client.length; i++) {
var firstName = client[i].getElementsByTagName("givenName")[0].childNodes[0];
var lastName = client[i].getElementsByTagName("familyName")[0].childNodes[0];
var oid = client[i].getElementsByTagName("oid")[0].childNodes[0];
var nhi = client[i].getElementsByTagName("nhi")[0].childNodes[0];
var dwelling = client[i].getElementsByTagName("dwelling")[0].childNodes[0];
var photo = client[i].getElementsByTagName("photo")[0].childNodes[0];
if (!photo) {
photo = "";
} else {
photo = photo.nodeValue;
}
firstName = firstName ? firstName.nodeValue : "";
lastName = lastName ? lastName.nodeValue : "";
oid = oid ? oid.nodeValue : "";
nhi = nhi ? nhi.nodeValue : "";
dwelling = dwelling ? dwelling.nodeValue : "";
var letterDwelling = dwelling ? dwelling[0].toUpperCase() : "";
var letterLastName = lastName ? lastName[0].toUpperCase() : "";
console.log(photo);
dataSource.add({photo: photo, firstName: firstName,lastName: lastName,oid: oid,nhi: nhi,dwelling: dwelling, letterDwelling: letterDwelling, letterLastName: letterLastName});
}
if (clientListViewHasNotLoaded) {
searchFilter = "lastName";
listGroup = "letterLastName"
console.log("e");
$("#theClientsList" + platform).append('<ul id="flat-listview' + platform + '" class="listView' + platform + '" style="width: 100%; margin-bottom:10px; margin-top:10px;"></ul>');
initListView({
field: "lastName",
operator: "startswith",
placeholder: "Search by last name"
}
);
$("#flat-listview" + platform).data("kendoMobileListView").setDataSource(dataSource);
clientListViewHasNotLoaded = false;
}
}
here is the code I'm using to create a web worker, before I take the next step and incorporate my above function:
the script (webServiceScript.js):
self.onmessage = function(event) {
var results = event.data;
// do something
// Done:
postMessage(results);
};
The calling code:
var worker = new Worker('scripts/webServiceScript.js');
worker.onmessage = function(event) {
// Do something with event.data, then hide the spinner.
app.showLoading();
};
app.hideLoading();
worker.postMessage({args: ' foo bar '});
I would like to incorporate my function at the top of the question into the script file (to be used in a web worker). When I incorporate my above function into the script, I need to pass my variable called xml.
Any help greatly appreciated, I'm struggling to understand the documentation here.
As we were discussing in comments, all you need to do is give the browser a chance to do a repaint. You can accomplish that with setTimeout() like this:
app.showLoading()
setTimeout(function() {
getTheClients(xml);
app.hideLoading();
}, 1);
You can't do setTimeout(getTheClients(xml), 1); because that calls getClients() right away and then passes the return result from that to setTimeout(). Instead, you have to pass just a function reference to setTimeout() as shown above.

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