JavaScript for loop not working? - javascript

I haven't really used loops before and I can't seem to figure out why my code isn't working. Was hoping for someone to help point me in the right direction.
return firebase.database().ref('Users/' + uid + "/PDR").once('value').then(function display(dataSnapshot) {
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++) {
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>' + num + '</td><td>' + dateFrom + '</td><td>' + dateTo + '</td><td>' + dbActivity + '</td></tr>'
})
}
})
Im trying to pull data from my Firebase backend and display it in a table, currently it only runs once.
Thanks for any help and advice!

Not sure what is going on in the dataSnapshot object, but first step in javascript debugging, is to add alert("Here"); in your code to see what (if anything) is being returned
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++){
alert("Here " + i); //Show me the loop variable
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
alert(num);
alert(dateFrom );
alert(dateTo );
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>'+ num +'</td><td>'+ dateFrom + '</td><td>'+ dateTo +'</td><td>'+ dbActivity +'</td></tr>'

Related

How come boolean value is logged as a checkbox is undefined when logged?

I am trying to log the value of the check variable which is column 11 it is a checkbox and should come up as true or false if it is ticked or not ticked. However I get a log saying that the value is undefined and I'm not quite so sure as to why this is.
could someone please help? I have put a comment for your reference.
function sendEmail() {
//setup function
var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
var AllValues = WholeRange.getValues();
var message = "";
for (i in AllValues) {
var CurrentRow = AllValues[i];
var EmailSent = CurrentRow[13];
//problem here
var check = CurrentRow[11];
Logger.log(check)
if (EmailSent == "sent")
continue;
//set HTML template for information
message +=
"<p><b>Timestamp by: </b>" + CurrentRow[1] + "</p>" +
"<p><b>Requester Email: </b>" + CurrentRow[2] + "</p>" +
"<p><b>Star Rating: </b>" + CurrentRow[3] + "</p>" +
"<p><b>Request Category: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Description: </b>" + CurrentRow[5] + "</p>" +
"<p><b>Label: </b>" + CurrentRow[6] + "</p>" +
"<p><b>Ticket ID: </b>" + CurrentRow[7] + "</p>" +
"<p><b>Comment: </b>" + CurrentRow[8] + "</p>" +
"<p><b>Status: </b>" + CurrentRow[9] + "</p><br><br>";
var setRow = parseInt(i) + StartRow;
ActiveSheet.getRange(setRow, 13).setValue("sent");
}
var SendTo = "email#email.org.au" + "," + "email#email.org.au";
var Subject = "CT IT feedback";
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: message,
});
}
As mentioned above, you are going to need to think about looping with nested for loop if you are getting values from a sheet.
I am not familiar with those functions you are using in your snippet, but for learning, I have included an example of how to step through a sheet below.
See example below.
var sheet = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
];
// Think of the above array as your sheet.
// You will step go 1, 2, 3, 4 and then step down a row
// to 5, 6, 7, 8 and so on.
var rows = sheet.length;
var rowCount;
for(var i = 0; i < rows; i++) {
rowCount = 0;
for(var j = 0; j < sheet[i].length; j++) {
rowCount += sheet[i][j];
}
// Finished calculating the row.
console.log(rowCount);
}
First, for...in is used for iterating over the properties of an object, not for arrays. I'd recommend using forEach instead. So try changing this:
for (i in AllValues) {
var CurrentRow = AllValues[i];
// Rest of code in loop
}
For this:
AllValues.forEach(function(CurrentRow) {
// Rest of code in loop
})
Apart from this, CurrentRow only goes till index 10, so it cannot access CurrentRow[11] and CurrentRow[13]. So, when you are defining WholeRange, you should take at least 14 columns:
var WholeRange = ActiveSheet.getRange(StartRow, 1, RowRange, 14);
Hope this is useful for you!

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Adding a table from database with javascript

I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.

why is only the last item is showing and not all of them

I am using the code below to call a php page that displays all the products and then parse them and display them on the string. This was working fine last week displaying all the results however now it has seem to have broken and only displays the last results from the database and after several days and painful hour staring at my screen i am starting to go mad and could do with some help.
function display(results) {
article = document.getElementById("homeArticle");
item = '';
for (var i = 0; i < results.length; i++){
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item = '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
};
article.innerHTML = item;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var results = JSON.parse(this.responseText);
display(results.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
if anyone could have any pointers that would help massively thank you!
You needed two variables. One that you use to build up the html string and one to hold each item from the results array.
Change your code to this:
function display(results) {
article = document.getElementById("homeArticle");
var html = '';
for (var i = 0; i < results.length; i++){
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
html += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
};
article.innerHTML = html;
}
That way you will append the html strings rather than overwrite the prior one.
Also consider making sure that each html element has a unique id, you could do this by appending i to the id e.g.
html += '<section id="homePageSection-'+i+'"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
Concat the item string, and don't use duplicate IDs, but classes instead:
item += '<section class="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
What you were doing is overwriting item on each iteration, which I why you only get the last one.
UPDATE
Forgot to provide the code for that last sentence I wrote. To avoid overwriting it, either use a different variable (as in the other answer), or simply assign the values directly without creating unnecessary variables, like this:
for (var i = 0; i < results.length; i++){
item += '<section class="homePageSection"> <p>Name:' +
results[i].P_NAME +
'</p><p>Description:' +
results[i].P_DESCRIPTION +
'</p><p>Price:' +
results[i].P_PRICE +
'</p></section>';
}

My code isn't working and I'm not sure why

Basically this is supposed to find the values in specific columns of the row and add them together to get a total and place that total in the cell specified. It is not working for some reason.
function rating(Irange,Q,Y,AG,AO,AW,BE,BM) {
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getDataRange().getValues();
var range = sheet.getRange(Irange);
var row = Irange.getRow();
var total = Number(values[row][8]) +
Number(values[row][9]) +
Number(values[row][10]) +
Number(values[row][11]) +
Number(values[row][16]) +
Number(values[row][17]) +
Number(values[row][18]) +
Number(values[row][19]) +
Number(values[row][24]) +
Number(values[row][25]) +
Number(values[row][26]) +
Number(values[row][27]) +
Number(values[row][32]) +
Number(values[row][33]) +
Number(values[row][34]) +
Number(values[row][35]) +
Number(values[row][40]) +
Number(values[row][41]) +
Number(values[row][42]) +
Number(values[row][43]) +
Number(values[row][48]) +
Number(values[row][49]) +
Number(values[row][50]) +
Number(values[row][51]) +
Number(values[row][56]) +
Number(values[row][57]) +
Number(values[row][58]) +
Number(values[row][59]) +
Number(values[row][64]) +
Number(values[row][65]) +
Number(values[row][66]) +
Number(values[row][67]);
return total;
}
It looks odd that you're doing
var range = sheet.getRange(Irange);
...and then not using that range for anything. Instead, on the next line, you have:
var row = Irange.getRow();
I haven't done virtually anything with Google Docs Spreadsheets, but perhaps that should be range.getRow() (no I), since Range objects have a getRow method. (Naturally I have no idea what your Irange argument is, but it looks like you're using it as a string when calling getRange(a1Notation)).

Categories

Resources