How to read a firebase Data using HTML5 and Javascript? - 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.

Related

Access to the specific content of an inside code of a script

Please, can anybody tell me how can I access to the value of "41" in this inner script of a website? I just tried this, but it doesnt work
I tried with:
var elem = document.getElementById("back-in-stock-helper");
I only need the number 41, and the example code I need to access is this
<script id="back-in-stock-helper">
var _BISConfig = _BISConfig || {};
_BISConfig.product.variants[0]['inventory_quantity'] = 41;
</script>
Thanks!
Solved:
var elem = document.getElementById("back-in-stock-helper");
var elem2 = elem.textContent;
var ult_pos = elem2.lastIndexOf('=');
var stock = elem2.substring(ult_pos);

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

How to update HTML table When updating Firebase?

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

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

Get String Value of Blob Passed to e.parameter in Apps Script

I'm using this code to get a blob passed to a function:
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
This is the error I get:
Execution failed: TypeError: Can not find getDataAsString function in
the Blob object.'arrayBlob'
How do I get the string value of this blob?
Here is my code:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = userProperties.getProperty('savedArray');
arrayList = JSON.stringify(arrayList);
var arrayBlob = Utilities.newBlob(arrayList);
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
arrayList = JSON.parse(arrayList);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
I'd like the solution worked with more than one user simultaneous using the script.
Update:
Add a global variable OUTSIDE of any function:
var arrayBlob = Utilities.newBlob("dummy data");
function showList(folderID) {
Code here ....
};
Check that the code has access to the blob:
function submit(e){
Logger.log("arrayBlob.getDataAsString(): " + arrayBlob.getDataAsString());
//More Code . . .
}
This solution eliminates the need of embedding a hidden element in the dialog box with a value of the blob.
You won't need this line:
panel.add(app.createHidden('arrayBlob', arrayBlob));
There are other changes I'd make to the code, but I simply want to show the main issue.
Old Info:
In the function showList(), the method getDataAsString() works on the blob named arrayBlob.
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
In the function, submit(), the same method does not work.
var arrayBlob = e.parameter.arrayBlob;
In the function showList(), the code is assigning a newBlob to the variable arrayBlob. So arrayBlob is available to have the getDataAsString() method used on it.
var arrayBlob = Utilities.newBlob(arrayList);
In the function, submit(), you are trying to pass the arrayBlob blob variable into the submit() function, and reference it with e.parameter.
If you put a Logger.log() statement in the submit() function.
function submit(e){
Logger.log('e: ' + e);
Logger.log('e.parameter` + e.parameter);
var arrayBlob = e.parameter.arrayBlob;
Those Logger.log statements should show something in them. If there is nothing in e.parameter, then there is nothing for the .getDataAsString() to work on.
It looks like you are putting the arrayBlob into a hidden panel.
panel.add(app.createHidden('arrayBlob', arrayBlob));
But when the object is getting passed to the submit(e) function, the arrayBlob might not be getting put into that object.
So, what I'm saying is, the:
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
Line may be perfectly good, but there is no arrayBlob there to work on. This hasn't fixed your problem, but do you think I'm understanding part of what is going on?
I'm not sure why you are using Blob's here at all, you could simply work with JSON instead.
However, if you have a reason to use Blobs, you can pass the JSON data through your form and create the Blob in your handler, as the modified code below does:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = UserProperties.getProperty('savedArray');
//get JSON data pass through form.
var arrayBlob = JSON.stringify(arrayList);
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
//include JSON Data in the form.
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = Utilities.newBlob(e.parameter.arrayBlob);
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
In the method you were using originally, the Blob itself was never included in the form, you were simply passing the string "Blob" around.
This is because the function createHidden(name, value); expects two strings as parameters, so it calls ".toString()" on the arrayBlob object, which returns the string "Blob".

Categories

Resources