How to update HTML table When updating Firebase? - javascript

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>");
});

Related

How to change title of an event?

I am trying to update the title of the events in the last 7 days in a specific calendar, when an user submits a form.
I have this code now:
function myFunction() {
var form = FormApp.openById('1g4gA7glYWRKOVqOi3z3qxyEGbJgaSg_2Jkry_uOp0Cc');
var responses = form.getResponses();
var len = responses.length;
var last = len - 1;
var items = responses[last].getItemResponses();
var email = responses[last].getRespondentEmail();
var equipment = items[1].getResponse();
var cal = CalendarApp.getCalendarsByName(equipment);
var d = new Date();
var ms = d.getTime();
var sevenDays = 7*24*60*60*1000;
var minus7daysMs = ms - sevenDays;
var minus7days = new Date(minus7daysMs);
Logger.log('Number of events: ' + minus7days);
var events = cal[0].getEvents(minus7days, d);
var title = events.getName;
Logger.log('Event title: ' + title);
events.setTitle('Returned');
}
However, I get that error when running the code: TypeError: events.setTitle is not a function myFunction # update.gs:22
I tried many different ways of doing it, but it always ends with an error. Could you please tell me what I am doing wrong?
Thank you very much for your help!
From your showing script, getEvents(startTime, endTime) returns CalendarEvent[]. And setTitle(title) is a method of Class CalendarEvent. In your script, at events.setTitle('Returned'), setTitle is used to an array. I think that the reason of your issue is due to this. When you want to change all events in events with setTitle('Returned'), how about the following modification?
From:
events.setTitle('Returned');
To:
events.forEach(e => e.setTitle('Returned'));
By this modification, the title of all events in events are changed.
References:
getEvents(startTime, endTime)
setTitle(title) of Class CalendarEvent

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

How to read a firebase Data using HTML5 and Javascript?

When I want to read the data of my Firebase, nothing appears.
I have tried to read the data using a script for this.
This is my HTML code:
<html>
<head>
<title>Javascript Firebase</title>
Humidity: <humidity></humidity><br>
Clock: <clock></clock><br>
</head>
<body>
and this is my script:
<script type="text/javascript">
var database = firebase.database('javascript-firebase-6567d');
var h document.querySelector('humidity');
var c = document.querySelector('clock');
var pad = function(x){
return x < 10 ? '0' +x : x;
}
var ShowClock = function() {
var d = new Date();
var h = pad(d.getHours());
var m = pad (d.getMinutes());
var s = pad (d.getSeconds());
c.innerHTML = [h,m,s].join(':');
}
setInterval(ShowClock,1000);
var myRef = Firebase('https://javascript-firebase-6567d.firebaseio.com/rooms');
myRef.on('child_changed',function(snapshot){
data = snapshot.val();
h.innerHTML = data.humidity;
});
</script>
The results that I hope is to see the changes that the child "humidity" shows but currently I can not see the results of the clock or the humidity
This code:
myRef.on('child_changed',function(snapshot){
data = snapshot.val();
h.innerHTML = data.humidity;
});
The child_changed event only fires when the data in the location changes. If you're trying to show the current child nodes under a location, you'll want to use child_added:
myRef.on('child_added',function(snapshot){
data = snapshot.val();
console.log(data);
});
The child_added fires immediately after attaching the listener for any existing child node, and then subsequently for any new nodes that are added.

Save items to different childs in firebase

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

Modal with title, subject, and time posted

This might be easy for some, but I'm struggling to make this work.
I created a modal that has title, subject (input area) and timestamp when you click submit.
I would like to output title, subject, and time posted as a list item <li></li>.
var main = function(){
$('.btn-primary').click(function(){
var title = $('#message-title').val();
var post = $('#message-text').val();
$('<li>').text(post).prependTo('.livefeed');
var currentTime = new Date();
var n = currentTime.toLocaleDateString();
document.getElementById("timestamp").innerHTML = n
$('#message-text').val();
});
}
$(document).ready(main);
Here is the Screenshot
try something like this
JAVASCRIPT
$('.btn-primary').click(function(){
var title = $('#message-title').val();
var post = $('#message-text').val();
var currentTime = new Date();
var n = currentTime.toLocaleDateString();
$('ul').append('<li>'+title+' '+post+' '+n+'</li>');
});

Categories

Resources