how to reverse order of xml using javascript - javascript

i want to reverse the order of this list using javascript i have tried different ways that i knew about it is
the below file show straight i want to reverse it.i dont know xml node much and how to get it reverse it totally
<messages>
<messageset>
<name>torje</name>
<time>1533904431</time>
<message>Vvvhjhf</message>
</messageset>
<messageset>
<name>moneyman</name>
<time>1533904437</time>
<message>njkjlmkmkl</message>
</messageset>
<messageset>
<name>anjali</name>
<time>1533904445</time>
<message>A hi fyi bk MLS egg FG ch bhi CDG jk IC</message>
</messageset>
</messages>
it the present code this shows order wise table like torje - Vvvhjhf , moneyman - njkjlmkmkl, anjali - A hi fyi bk MLS egg FG ch bhi CDG jk IC this should be reverse first anjali's msg then moneyman then torje's (sorry for bad typing in message)
function fetch() {
setTimeout( function() {
loadDoc()
fetch();
}, 100);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "../clubs/club.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}

Can create an array and push each data row into the array then Array#reverse() that array and convert back to string using Array#join()
function myFunction(xml) {
var rowsArray =[]
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
// new variable `row`
var row = "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
// add row to array
rowsArray.push(row)
}
// reverse and return array to string
table += rowsArray.reverse().join('');
document.getElementById("demo").innerHTML = table;
}

Currently your for loop processes the messages in standard order.
for (i = 0; i < x.length; i++) {
You could just reverse this loop:
for (i = x.length - 1; i >= 0; i—-) {

Related

Javascript for loop only giving one output

I've been toying with this for far too long...
function OnSearch() {
var text_in = sVal()
var tArea = document.getElementById("SearchResults")
var loadstr = "Loading results for "
var xhttp = new XMLHttpRequest();
var altStr = ""
var sendstr = ""
var urls = []
for (i = 0; i < ciphersOn.length; i++) {
aCipher = ciphersOn[i]
sendstr += "/search="+text_in+""
sendstr += '/name=' + aCipher.Nickname + ''
sendstr += '/letters='
for (x = 0; x < aCipher.cArr.length; x++) {
sendstr += String.fromCharCode(aCipher.cArr[x])
}
sendstr += "/cipher="
for (x = 0; x < aCipher.vArr.length; x++) {
if(aCipher.vArr.length == x+1){
sendstr += aCipher.vArr[x]
} else sendstr += aCipher.vArr[x] + "-"
}
/* send http GET and bring back info to a new list, then clear sendstr before it loops again. */
urls.push(sendstr)
sendstr=""
}
for(i = 0; i < urls.length; i++) {
xhttp.open("GET", "http://localhost:8000" + urls[i] + "", true);
xhttp.send();
}
loadstr += '"' + text_in + '"' + sendstr + '' + urls.length + '' + aURL + '' /* the purpose of this is so I can see what is happening to my code */
tArea.innerHTML = loadstr
}
I have no clue why that for loop at the end only sends one GET request. Please, spare me my sanity... I just don't get it. The array "urls" contains the information I need, and the variable "sendstr" works perfectly well... Why then does my terminal only show that the first result is being given?
Each XMLHttpRequest can only send one request. As stated in MDN, calling open on an already open request is equivalent to aborting the request. So, create a new XMLHttpRequest for each loop:
for(i = 0; i < urls.length; i++) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8000" + urls[i], true);
xhttp.send();
}
Alternatively, migrate to fetch:
for(i = 0; i < urls.length; i++) {
fetch("http://localhost:8000" + urls[i]);
}

How to store the values in hashmap in javascript

I am parsing xml file in javascript and i am extracting all its values
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "/ccm/rpt/repository /workitem?fields=workitem/projectArea/*", true);
xmlhttp.send();
}
function myFunction(xml) {
var x,y,j, i, xmlDoc, txt,txt1;
xmlDoc = xml.responseXML;
txt = "";
txt1="";
x = xmlDoc.getElementsByTagName("contextId");
for (i = 0; i< x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
y = xmlDoc.getElementsByTagName("name");
for (j = 0; i< y.length; j++) {
txt1 += y[j].childNodes[0].nodeValue;
}
}
and now my target is to store the value of name as key and contextId as value (HashMap concept) , So is it possible to achieve the same,Also please let me if my question sounds ambiguous
Thanks in advance!!
You can add properties to objects as if they were hashmaps, have a look at this example:
var myObj = {prop1: 12};
var propName = "prop2";
myObj[propName] = 10;
console.log(myObj);
Which outputs:
{prop1: 12, prop2: 10}
In your example, lets assume x and y are of equal length, then we can add to the object in a single loop:
var x,y,j, i, xmlDoc, myHashMap;
xmlDoc = xml.responseXML;
myHashMap = {};
x = xmlDoc.getElementsByTagName("contextId");
y = xmlDoc.getElementsByTagName("name");
for (i = 0; i< x.length; i++) {
var value = x[i].childNodes[0].nodeValue;
var key = y[i].childNodes[0].nodeValue;
myHashMap[key] = value;
}
console.log(myHashMap);

Calculations on parsed JSON values produce NaN

I have a problem with some code. I started building a plugin for Chroma to insert data using JSON, but NaN is displayed to me.
My file content.js
var xmlhttp = new XMLHttpRequest();
var url = "http://rlinkit.neteasy.pl/abc.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr= Array();
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
for (i in arr) {
for(j in arr[i] ){
for(p in arr[i][j]){
out = arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].bid + arr[i][j][p].ask + '<br>';
}
}
}
document.getElementById("id01").innerHTML = out;
}
My CodeHTML:
<div id="id01"></div>
<script src="content.js"></script>
My Output:
Edit (When I give the code - nothing is displayed.):
function myFunction(arr) {
var out = "";
var i;
var j;
var p;
for (var i = 0; i in arr.length; i++) {
for(var j = 0; j in arr[i].length; j++ ){
for(var p = 0; p in arr[i][j].length; p++){
out += arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].buy + arr[i][j][p].sell + '<br>';
}
}
}
document.getElementById("id01").innerHTML = out;
}
To iterate over a JavaScript array, either use a for ... of loop or a traditional for loop. The syntax in your updated function (specifically, i in arr.length) is invalid JavaScript (looks like Python?).
Providing example data would help to improve this answer, but try some version of the following (updated to use ES6 let syntax, which you may want to revert to var):
function myFunction(arr) {
let out = "";
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
for (let p = 0; p < arr[i][j].length; p++) {
out += arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].buy + arr[i][j][p].sell + "<br>";
}
}
}
document.getElementById("id01").innerHTML = out;
}

Tableau Javascript API

Can you explain the functions below:
viz = new tableau.Viz(containerDiv, url, options);
function listenToMarksSelection() {
viz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, onMarksSelection);
}
function onMarksSelection(marksEvent) {
return marksEvent.getMarksAsync().then(reportSelectedMarks);
}
function reportSelectedMarks(marks) {
var html = "";
for (var markIndex = 0; markIndex < marks.length; markIndex++) {
var pairs = marks[markIndex].getPairs();
html += "<b>Mark " + markIndex + ":</b><ul>";
for (var pairIndex = 0; pairIndex < pairs.length; pairIndex++) {
var pair = pairs[pairIndex];
html += "<li><b>Field Name:</b> " + pair.fieldName;
html += "<br/><b>Value:</b> " + pair.formattedValue + "</li>";
}
}
}
This function just listen the selected mark
This one throw the selection in reportSelectedMarks
It take the marks and write it in an HTML file in a '<'li'>'.
The fieldname would probably be a String and in the value it depend what you are workin with.
So basically these functions would be useful to dynamically print a selected mark on a graph or something like that and print a fielname and a value for that one.

passing page scraped data in the URL

In my Chrome extension, I'm trying to scrape information from the current tab (in content.js) and send it as parameter to the provided URL (background.js). It seems like I can scrape everything from the tab and append it to the URL except the values of input tags. Here's my code:
content.js:
var elements = new Array("form","h1","input","td","textarea","time","title","var");
//declare an array for found elements
var foundElements = new Array();
//declare an array for found ids
var foundIds = new Array();
//this counter is used to hold positions in the element array.
var elementCounter = 0;
//this counter is used to hold positions in the foundIds array
var idsCounter = 0;
//this counter is used to hold positions in the classCounter array.
var classCounter = 0;
//and we're going to output everything in a giantic string.
var output = "URL=" + document.URL;
//scrape the page for all elements
for (var i = 0; i < elements.length; i++)
{
var current = document.getElementsByTagName(elements[i]);
if(current.length>0)
{
for (var z=0; z<current.length; z++)
{
var inTxt = current[z].innerText;
output += "&" + elements[i] + "=" + inTxt;
}
elementCounter++;
//now that we have an array of a tag, check it for IDs and classes.
for (var y = 0; y<current.length; y++)
{
//check to see if the element has an id
if(current[y].id)
{
//these should be unique
var hit = false;
for (var x = 0; x<foundIds.length; x++)
{
if(foundIds[x]==current[y].id)
{
hit=true;
}
}
//if there was no hit...
if(!hit)
{
foundIds[idsCounter]=current[y].id;
idsCounter++;
var currVal = current[y].value;
output+="&" + current[y].id + "=" + currVal;
}
}
//now we pull the classes
var classes = current[y].classList;
if(classes.length>0)
{
for (var x = 0; x<classes.Length; x++)
{
var hit = false;
for (var z = 0; z<foundClasses.length; z++)
{
if(foundClasses[z]==classes[x])
{
hit=true;
}
}
//if there was not a hit
if(!hit)
{
foundClasses[classCounter]=classes[x];
classCounter++;
output+="&" + classes[x] + "=";
}
}
}
}
}
}
chrome.runtime.sendMessage({data: output});
background.js:
var output2;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
output2 = "text_input1=";
output2 += request.data;
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
sendMessage();
});
});
});
Does anyone know why the input tags values are passed as blank?
Because you're trying to get the input text by using current[z].innerText.
However, you have to use current[z].value for inputs.

Categories