How can I save data to different childs in a firebase?
I push items to a firebase using onclick function and if/else statements for creating different categories.
Example
Button1 click -> push data from inputform to child1 in firebase,
Button2 click -> push data from inputform to child2 in firebase....
Problem
The item is pushed to one child only (e.g. ref0).
Everytime I push further items into the firebase, there appended to the ref0 child and not assigned to a new child (e.g. ref1).
Unfortunately I canĀ“t find specific information for solving this issue.
Would be great if you can support me.
Check my Code for more specific information.
//create firebase reference
var dbRef = new Firebase('https://firebaseurl.firebaseio.com/');
var ref0 = dbRef.child('ref0');
var ref1 = dbRef.child('ref1');
var ref2 = dbRef.child('ref2');
var ref3 = dbRef.child('ref3');
var showAllRefs = ref0, ref1, ref2, ref3;
//load all contacts (limited to last 5 items)
showAllRefs.limitToLast(5).on("child_added", function(snap) {
snap.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var childData = childSnapshot.val();
//create divs from database-elements
var card = document.createElement('div');
card.setAttribute('class', 'linkprev');
$('#content').prepend($(card));
var cardtitle = document.createElement('div');
cardtitle.setAttribute('class', 'cardtitle');
cardtitle.innerHTML = childData;
card.appendChild(cardtitle);
});
$(document).ready(function(){
document.guteUrls.execute('linkprev');
});
});
//save contact
//save in database contacts
var elements = $('.f');
//console.log(elements);
//save items to firebase(childs)
var buttonPressed = function( event ) {
event.preventDefault();
//url validation from inputfield using Regex
var valpattern = new RegExp('^(http|https)://'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
var valselect = document.getElementById('url');
var val = valpattern.test(valselect.value);
//save in database to different childs on buttonclick
if(val && document.querySelector(".f1")){ref0.push({name: document.querySelector('#url').value})
contactForm.reset();}
else if(val && document.querySelector(".g1")){ref1.push({name: document.querySelector('#url').value})
contactForm.reset();}
else if(val && document.querySelector(".h1")){ref2.push({name: document.querySelector('#url').value})
contactForm.reset();}
else if(val && document.querySelector(".i1")){ref3.push({name: document.querySelector('#url').value})
contactForm.reset();}
else {
alert('Oops');}
};
for (var i = 0; i < elements.length; i++) {elements[i].addEventListener("click", buttonPressed, false);}
Thanks in advance
Ben
Related
I have a Google form the information that is submitted is from students and faculty. The form has a trigger to run the function every time information is submitted. I want to copy all the submitted information to different tabs. One with staff members and one with student info. I can copy all the information into one tab, but when I try to separate it I am not able to get the results I need.
Any tips or guidance would be much appreciated.
function copyRowsWithCopyto(){
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = spreadSheet.getSheetByName('Entrega_Dispositivos');
var sourceRange = sourceSheet.getDataRange();
var studentSheet = spreadSheet.getSheetByName('Student_Copy');
var staffSheet = spreadSheet.getSheetByName('Staff_copy');
var lr = sourceSheet.getLastRow();
var data = sourceSheet.getRange("A2:AS" + lr).getValues();
for(var i = 0;i<data.length;i++){
var rowData = data[i];
var status = rowData[2];
if(status == "Student" && status != "Staff"){
sourceRange.copyTo(studentSheet.getRange(1, 1));
} else {
sourceRange.copyTo(staffSheet.getRange(1, 1));
}
}
}
function onFormSubmit(e) {
const itemResponses = e.response.getItemResponses();
const status = itemResponses[1].getResponse();
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (status === 'Student') {
ss.getSheetByName('Student_Copy').appendRow(e.values);
}
else {
ss.getSheetByName('Staff_copy').appendRow(e.values);
}
}
You can simply put 2 queries, one in each tab, to separate student and staff, without any scripts !
I have a function defined in a file called database.js whenever a certain page is loaded. An associated page is loginpage.ejs, which starts with a blank table element.
In this function in database.js, I retrieve values from DynamoDB in a loop, parsing each entry using the JSON parse function.
Here is the function.
var get_restaurants = function(route_callbck){
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
var async = require('async');
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "restaurants"
};
var count = 0;
docClient.scan(params).eachPage((err, data, done) => {
if (data != null) {
for (let index = 0; index < data.Items.length; index++) {
const element = data.Items[index];
var str = JSON.stringify(element);
var x = JSON.parse(str);
//var x is the whole item- how do I put this in a table?
console.log(x);
}
}
done();
});
};
I have an ejs file with a table defined as shown. loginpage.ejs
<table name="restaurants"></table>
So console.log prints each item... but I want to add each item to the table named restaurants in the ejs file. For now I'd simply like to add the whole string to the table- so one entry for each item as I iterate. I can figure out dissecting the JSON later.
I'm not sure how I can place this function in the ejs file perhaps and call it upon loading, or if that will even work the same way? Any help would be greatly appreciated!
maybe, var x = [{no:1, title:'hh', date:'2018-11-2' ..}, {..etc}]. right?
after get data,
in case jquery,
$("#restaurants").append(`<tr>
<td>no</td>
<td>title</td>
<td>date</td>
</tr>`)
for(let i = 0; i<x.length; i++){
$("#restaurants").append(`<tr>
<td>${i}</td>
<td>${x.title}</td>
<td>${x.date}</td>
</tr>`)
}
if you use vanila javascript, point is same.
you should control document.dom after get data.
Without knowing the form you get data in:
let restoTable = document.getElementById('restaurants');
var get_restaurants = function(route_callbck){
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
var async = require('async');
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "restaurants"
};
docClient.scan(params).eachPage((err, data, done) => {
if (data != null) {
for(var index=0; index<data.Items.length; index++) {
var record = data.Items[index];
var newRow = restoTable.insertRow(index); //insert new row to the end of a table
var dataArr = Object.values(record); //convert record to an array, if needed. Perhaps you already have...
for(var c=0; c<dataArr.length;c++){
var newCell = newRow.insertCell(c); //insert new cell to the end of the row...
var newText = document.createTextNode(dataArr[c]); //...and fill it
newCell.appendChild(newText);
}
}
}
});
};
I'm using child_added and child_changed. The child added works perfectly fine, but the child_changed makes a duplicate in my table. Please help me overcome this. Here is my code:
var rootRef = firebase.database().ref().child("REPORTS").child(date);
rootRef.on("child_added", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
rootRef.on("child_changed", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
How can I update my table when a certain value was updated in firebase
Instead of appending a new HTML element, the code that handles child_changed should update the existing HTML element. The easiest way to do this is by ensuring you give the HTML element an id based on snapshot.key in child_added:
var rootRef = firebase.database().ref().child("REPORTS").child(date);
rootRef.on("child_added", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr id='"+snapshot.key+"'><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
Then you can look the element up by its id/key in child_changed and update it:
rootRef.on("child_changed", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#"+snapshot.key).replaceWith("<tr id='"+snapshot.key+"'><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
first of all, this is the case:
I do have a masterdata sheet with lots of employee details (database). Column G contains email-adresses. I try to find a way to separate/select the lines for which the email-address matches the active user email-address. Without any opportunity for the user to change anything.
I tried different approaches with Query and IMPORTRANGE within the spreadsheet (e.g. =QUERY(IMPORTRANGE("101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U";"Data!A1:AC100"); "Select Col1,Col2,Col3,Col4 where Col7='Pascal Richter'"). But in this case the user would be able to change the name.
So I tried to build a webapp with the following functionalities:
the script identifies onOpen the activeUser
Button "send me data" starts the function createSSwithselectedData ()
the function createSSwithselectedData () creates a new spreadsheet
the function createSSwithselectedData () looks up the lines where the activeUser and the email in column g matches
the function createSSwithselectedData () transfers the identified data to the new spreadsheet
the activeUser gets an email with a link to the new spreadsheet
This is a dummy of the masterdata sheet.
Help is highly appreciated :)
// Log the email address of the active user
var email = Session.getActiveUser().getEmail();
Logger.log(email);
var DatabaseID = "101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U";
var Data = SpreadsheetApp.openById("101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U").getDataRange().getValues();
Logger.log(Data);
function doGet() {
var app = UiApp.createApplication();
// create a button and give it a click handler
var button = app.createButton("Send me data!").setId("button");
button.addClickHandler(app.createServerHandler("createSSwithselectedData"));
app.add(button);
return app;
}
function createSSwithselectedData(email) {
var app = UiApp.getActiveApplication();
app.getElementById("button").setText("Data is on the way");
return app;
var SheetTemplate = "1Z-ECGaRXaO8mEjTCx74z4sXOc_B7ZU81qfhtVJ3TAic";
var SheetName = "Jobgroup validation - ";
var newSheetName = SheetName + email ;
var folderId = "0B45D8-yA6A-HTWF1MjNhZW1VaXM"
var destination = DriveApp.getFolderById(folderId);
var copyId = DriveApp.getFileById(SheetTemplate).makeCopy(newSheetName, destination).getId();
var copySheet = SpreadsheetApp.openById(copyId);
// this is a new array to collect data
var target = new Array();
for(n=0;n<data.length;++n){ // iterate in the array, row by row
if (data[n][7]==email){ ; // if condition is true copy the whole row to target
target.push(data[n]); // copy the whole row
} //if
} //for
copySheet.getRange(1,10,target.length,target[0].length).setValues();
// Save and close the temporary document
copySheet.saveAndClose();
var url = copySheet.getUrl(); //DriveApp.getFileById(newFileId);
var link = "" + newSheetName + "";
var subject = "Jobgroup validation - " + email;
var body = "<p>You requested your team details. Please check the content.</p></br> " + link;
MailApp.sendEmail({to: email, subject: subject, htmlBody: body, name: alias, noReply: true});
}
I know this questions has been asked several times . But I have not been able to find out the solution after getting error multiple times . this is the code of my indexed db
request.onupgradeneeded = function(event) {
var db = event.target.result;
var upgradeTransaction = event.target.transaction;
var objectStore = db.createObjectStore("todostore", {keyPath: "timestamp"});
UserFunction();
};
function UserFunction(){
var ObjectStore = db.transaction("todostore").objectStore("todostore");
var index = ObjectStore.createIndex("ixName", "fieldName");
}
Failed to execute 'createIndex' on 'IDBObjectStore': The database is not running a version change transaction.
I am calling this function of button click I want to add index with value when a button is clicked
<button onclick="UserFunction()">createIndex</button>
You can only change the schema of the database during a version upgrade. Something like this is plausible:
function OnClick() {
// assumes db is a previously opened connection
var oldVersion = db.version;
db.close();
// force an upgrade to a higher version
var open = indexedDB.open(db.name, oldVersion + 1);
open.onupgradeneeded = function() {
var tx = open.transaction;
// grab a reference to the existing object store
var objectStore = tx.objectStore('todostore');
// create the index
var index = objectStore.createIndex('ixName', 'fieldName');
};
open.onsuccess = function() {
// store the new connection for future use
db = open.result;
};
}
Code in UserFunction() call, is starting a new transaction, while already a transaction is going on in "upgradeneeded" listener.
So new transaction should be started, after objectStore.transaction completes.
Here is the JSFiddle : Solution is here
function UserFunction(){
var request = window.indexedDB.open("MyTestDatabase", 3);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var upgradeTransaction = event.target.transaction;
var objectStore = db.createObjectStore("todostore", {keyPath: "timestamp"});
objectStore.transaction.oncomplete = function(event) {
addIndex(db);
};
};
}
function addIndex(db){
var ObjectStore = db.transaction("todostore").objectStore("todostore");
var index = ObjectStore.createIndex("ixName", "fieldName");
}