I'm trying to create an app that retrieves data from Firebase and show it in a table using JavaScript. The problem is that it’s showing me “undefined” in the app and in the console and when I try to print the values directly from the functions they contain a value, so can anyone please help me with this?
This is my code:
function doSomething() {
var something = firebase.database().ref('*****');
//comment selection
something.on('value', function gotData(data) {
var values = data.val();
var keys = Object.keys(values);
var i = 0;
while (i < keys.length) {
var k = keys[i];
var comments = values[k].comment;
var idU = values[k].id;
var idS = values[k].idservice;
var nom = getuser(idU);
var service = getservice(idS);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var t = document.createTextNode(i + ':' + comments);
var t2 = document.createTextNode(nom);
var t3 = document.createTextNode(service);
td.appendChild(t);
td2.appendChild(t2);
td3.appendChild(t3);
tr.appendChild(td);
tr.appendChild(td2);
tr.appendChild(td3);
document.getElementById("commentsection").appendChild(tr);
i++;
}
}, errData);
}
function getuser(IdU) {
var users = firebase.database().ref('******');
users.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var j = 0;
while (j < keys.length) {
var k = keys[j];
if (k === IdU) {
var name = values[k].nom;
console.log(name);
return name;
break;
} else {
console.log('not found');
break;
}
j++;
}
}, errData);
}
function getservice(IdS) {
var service = firebase.database().ref('******');
service.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var s = 0;
while (s < keys.length) {
var k = keys[s];
if (k === IdS) {
var nomservice = values[k].nomservice
console.log(nomservice);
return nomservice;
break;
} else {
return false;
}
s++;
}
}, errData);
}
function errData(err) {
console.log('error!');
console.log(err);
}
This is a screenshot for what I get:
Related
Hello guys below is a link to my google sheet database please i want to implement a feature that will allow me pull data from google sheets to html table when they select a date range e.g( from 12/1/2019 to 12/7/2019) and a specific state(e.g California) will display only the records for california that fall into the date range please i will be grateful if i have the solution to this as it is a bottle neck for me to deliver on this project. Thanks[
code.gs
function getTableData(fac, dataaaa) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var allSheetRowData=sheet.getDataRange().getValues();
var sheetHeaderData=allSheetRowData[0];
var dateColIndex = sheetHeaderData.indexOf("Date");
var stateColIndex = sheetHeaderData.indexOf("state");
var array=[];
var hey = fac.toString();
array.push(sheetHeaderData);
var dat = dataaaa.toString();
var rowData;
for(var i=1; i<allSheetRowData.length-1 ;i++){
if((allSheetRowData[i][dateColIndex]) == dat && allSheetRowData[i][stateColIndex]== hey){
rowData=allSheetRowData[i];
array.push(rowData);
Logger.log(rowData);
break;
}
}
return array;
}
function include (filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function extractAction () {
var stateVal = document.getElementById ('extractstate');
var datepic = document.getElementById ('extractdate').value;
if (stateVal[stateVal.selectedIndex].value == '') {
alerterror ('Please choose the state');
} else if (datepic == '') {
alerterror ('Please choose the Date');
} else {
var dataaaa = datepic.toString ();
var fac = stateVal.options[stateVal.selectedIndex].text;
alertsuccess ('You successfully pulled the data');
google.script.run
.withSuccessHandler (generateTable)
.getTableData (fac, dataaaa);
//generateTable();
}
}
function generateTable (dataArray) {
var newarray = TwoDimensional (dataArray, 2);
var newarray_2 = newarray.slice (1);
newarray_2.forEach (function (r) {
r.forEach (function (val, key) {
var arrayhead = newarray[0];
var count = 0;
console.log (r);
var tbody = document.getElementById ('tableID');
var row = tbody.insertRow (count++);
var cell1 = row.insertCell (0);
var cell2 = row.insertCell (1);
cell1.innerHTML = arrayhead[key];
cell2.innerHTML = val;
});
});
}
<table>
<tbody id="tableID">
</tbody>
</table>
html table like this
function getTableData(fac, data) {
if(fac && data) {
var sh=SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
hA.forEach(function(e,i){hObj[e]=i;})
var array=[];
array.push(hA);
for(var i=1; i<vA.length-1 ;i++){
if((vA[i][hObj['date']])==data && vA[i][hObj['state']]==fac){
array.push(vA[i]);
}
}
return array;
}
}
You were using 'Date' for getting date header index but that doesn't agree with you image.
I would do it like this:
On the server side:
function getTableData(fac, data) {
if(fac && data) {
var sh=SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
var html='<style>td,th{border:1px solid black}</style><table><tr>';
hA.forEach(function(e,i){hObj[e]=i;html+='<th>' + e + '</th>';});
html+='</tr>';
var array=[];
array.push(hA);
for(var i=1; i<vA.length-1 ;i++){
if((vA[i][hObj['date']])==data && vA[i][hObj['state']]==fac){
html+='<tr>';
vA[i].forEach(function(e,i){
html+='<td>' + e + '</td>';
})
html+='</tr>';
array.push(vA[i]);
}
}
html+='</table>';
return {array:array,html:html};
}
}
on the client side:
google.script.run
.withSuccessHandler (function(obj){
document.getElementById ('tableID').innerHTML=obj.html;
})
.getTableData (fac,dataaaa);
I am trying to count the number of rows between two rows containing particular words in google sheets. But I am getting the following error:
Cannot convert [object Object] to (class). (line 41, file "Code")
I have written the following code on the google app script:
function search(SPREADSHEET_ID, SHEET_NAME, word) {
var locatedCells = [];
var ss = SpreadsheetApp.openById(SPREADSHEET_ID);
var searchLocation = ss.getSheetByName(SHEET_NAME).getDataRange().getValues();
//Loops to find the search term.
for (var j = 0, jLen = searchLocation.length; j < jLen; j++) {
for (var k = 0, kLen = searchLocation.length; k < kLen; k++) {
var find = word;
if (find == searchLocation[j][k]) {
locatedCells.push({ 'found': (j + 1)});
}
}
}
// Logger.log(locatedCells);
return(locatedCells)
}
function footerlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Footers"
var footerlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(footerlocation);
return(footerlocation)
}
function keywordlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Keyword Page Redirects to Implement"
var keywordlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(keywordlocation);
return(keywordlocation)
}
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()
var endrow= keywordlocation()
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}
I would appreciate if someone could help me with this.
I was able to figure out the solution, change the count function to the following:
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()[0]['found']
var endrow= keywordlocation()[0]['found']
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}
I need help to get a list of unique sorted value of a specific column (column B).
This is my try (It doesn't work), can you help me to find the error?
I'm not able to get the correct range in [object] format...
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function UniqueRange() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('Prova')
var drng = sht.getDataRange();
var rng = sht.getRange(2,2, drng.getLastRow()-1,1);
var rngA = rng.getValues();
var shtout = s.getSheetByName('Nuovo');
var rngout = shtout.getRange(2,1,rngA.length,1)
var rngB = rngout.setValues(rngA);
var i = 0; i < rngA.length; i++
var rngB = rngB[i];
var unique = rngB.filter( onlyUnique );
}
Solution by Bellian:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function uniquevalues(){
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('Prova')
var drng = sht.getDataRange();
var rng = sht.getRange(2,2, drng.getLastRow()-1,1); //range that contain all values
var rngA = rng.getValues();
var unique = [];
for(var i = 0; i < rngA.length; i++) {
var unique = unique.concat(rngA[i+1]);
}
unique = unique.filter(onlyUnique);
Logger.log(unique)
}
function getUniqueSortedArray(sheetname,column,datastartrow)
{
if(sheetname && column && datastartrow)
{
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName(sheetname);
var cntRg=cntSh.getDataRange().sort({column:column,ascending:true});
var vA=cntRg.getValues();
var uiA=[];
for(var i=datastartrow-1;i<vA.length;i++)
{
if(uiA.indexOf(vA[i][column-1])==-1)
{
uiA.push(vA[i][column-1]);
}
}
return uiA;
}
else
{
return 'Invalid Inputs';
}
}
And this is my modification of your code.
function UniqueSortedRange()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getSheetByName('Prova')
var rg=sh.getDataRange().sort({column:2,ascending:true});
var vA=rg.getValues();
var sh0=ss.getSheetByName('Nuovo');
var luneeko=[];
for(var i=1;i<vA.length;i++)
{
if(luneeko.indexOf(vA[i][1])==-1)
{
luneeko.push(vA[i][1]);
}
}
return luneeko;
}
Below is my code. if we use set timeout function we got all data but we not use we are not getting inspection data which is coming from my local db. i want use deferred and promises in my code. Thanks in advance.
function onclickToCall() {
this.$('.check-list > .check-list-box').each(function (i) {
var j = i + 1;
var answer_req = $(this).attr("data-isReq");
var checklist_guid = $(this).attr("data-guid");
var question_type = $(this).attr("data-type");
var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
var notes = $(this).find('#txtAreaNotes_' + j).val();
var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
var appConfig = DriverConnectApp.State.get('config_settings');
var item = {};
item.checklist_guid = checklist_guid;
item.yes_no = yes_no;
item.attachment_url = attachment_url;
item.notes = notes;
if (question_type == 2) { // For Vehical visual inspection
var dataPromise = that.getInspectionData(checklist_guid);
dataPromise.done(function (response, vh_image) {
var inspectionItem = {};
inspectionItem.vh_url = vh_image;
inspectionItem.details = response;
item.vh_inspection = inspectionItem;
that.detailsArr.push(item);
});
} else {
item.vh_inspection = {};
that.detailsArr.push(item);
}
});
// after finish and push all data we need to call function here
test();
}
getInspectionData: function (checklist_guid) {
var that = this;
var deferred = $.Deferred();
that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
var details = [];
if (data.length) {
var img = data[0].vh_image;
var arr = JSON.parse(data[0].vh_details);
for (var k = 0; k < arr.length; k++) {
var items = {};
items.number = arr[k].number;
items.notes = arr[k].notes;
items.attachment_url = arr[k].attachment_url;
details.push(items);
}
deferred.resolve(details, img);
} else {
deferred.resolve(details, img);
}
});
return deferred.promise();
}
Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}