Outputting Firebase database data to webpage - javascript

I am trying to output all the data from my Firebase Database to a blank webpage. I currently have it printing out in the chrome console using the code below.
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
Instead of it printing to the console I want it to print to the actual webpage itself. Struggling since there is not much documentation around Firebase itself.
Here is my entire code for the near blank html page im trying to output the Firebase database data to. I have also included a picture of the structure of my Firebase database.Here
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src = "https://www.gstatic.com/firebasejs/4.6.2/firebase-app.js">
</script>
<script src = "https://www.gstatic.com/firebasejs/4.6.2/firebase-auth.js">
</script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-database.js">
</script>
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="img/membrain.ico">
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
const config = {
.........
};
firebase.initializeApp(config);
</script>
</head>
<body>
<h1>Firebase Database</h1>
<script>
var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
</script>
</body>
</html>

Related

Inconsistent HTTP trigger behaviour to Firebase Cloud Functions

I'm having trouble reliably triggering a Firebase Cloud Function via the HTTP trigger method. It doesn't work in all browsers, and sometimes only works if you reload the page. The html webpage is hosted with Firebase Hosting.
Premise is simple, main html page has a button which when pressed, sends the HTTP request to the Cloud Function, and then navigates to another page saying done. The Cloud Function sends an FCM notification and works reliably when manually using the HTTP request url.
Is there something wrong with my HTTP request in scripts.js? What would make this very inconsistent behaviour? It works generally in Chrome, not in Firefox, and sometimes in Edge.
index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel=icon href=favicon.ico>
<title>Title</title>
</head>
<body>
<h1>New heading</h1>
<input type="button" value="Send FCM" onclick="doThing()">
<script src="scripts.js"></script>
</body>
</html>
scripts.js looks like this
var request = require('request')
function doThing(){
const url = '<HTTP request URL>';
request(url, function(error, response, body){
if (!error && response.statusCode == 200){
window.location.href = "outro.html";
}
})
}
and outro.html looks like this;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<body>
<h1>Cya</h1>
</body>
</body>
</html>
For clarity, this is the Cloud Function script:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.https.onRequest((request, response) =>{
var topic = 'all';
var payload = {
notification:{
title: 'Title!',
body: 'Test!'
},
};
return admin.messaging().sendToTopic(topic, payload).then((res) =>{
response.status(200).send("ok");
return console.log("Success:");
}).catch((err) =>{
console.log("Error: ", err);
response.status(500).send("bad");
});
});
All are deployed with firebase deploy.

podio API javascript

I m trying to connect Podio API with a webpage.
I have this error : "podio.hasAuthError is not a function", but i don t know what to do....
I show you my (basic) code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="lib/podio-js/dist/podio-js.js"></script>
<script type="text/javascript">
var podio = new PodioJS({ authType: 'client', clientId: 'foo'});
var redirectURL = 'http://foo';
// isAuthenticated either gets the cached accessToken
// or will check whether it is present in the hash fragment
podio.isAuthenticated().then(function(){
// ready to make API calls...
}).catch(function(){
if (podio.hasAuthError()) {
console.log(podio.getAuthError());
} else {
// start authentication via link or redirect
console.log(platform.getAuthorizationURL(redirectURL));
}
});
</script>
</head>
<body>
</body>
</html>

Why is the js and html code not running the search query?

I am trying to use Youtube's api, and run a search query to retrieve the videos found. When I run the js or the html, nothing is printing. The authentication key is correct. When I run the js file all it says is [Finished in 0.4s]. When I run the html file nothing shows up.
js file
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad() {
gapi.client.setApiKey('hidden');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'dog'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response) {
showResponse(response);
}
search html code
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
By default the return value for the video link is the video ID inside the json response format.
"id": {
"kind": "youtube#video",
"videoId": "dgVKzvO5zNc"
}
you can filter the json response and create a work around like a link, here is an example:
request.execute(function(response) {
var items = response.result.items;
for(i in items){
var vidID = items[i].id.videoId;
var link = '' + "link"+[i] + '<br>';
document.getElementById('search-container').innerHTML += link;
}
});
html file
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<div id="buttons"><input id="query" value='cats' type="text"/><button id="search-button" onclick="search()" >Search</button></label>
</div>
<div id="search-container">
</div>
</body>
</html>

Phonegap build Geolocation not working

js: i use simple alert to display the location, and use phonegap build to compile. Device ready alert is shown! But not any other alerts!
document.addEventListener("deviceready", getDeviceLocation , false);
function getDeviceLocation () {
alert('device ready');
navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true } );
}
function showPosition(position) {
alert('show postion called');
alert("Latitude: " + position.coords.latitude +
"Longitude: " + position.coords.longitude);
}
function showError(error) {
alert('show error called');
alert("Errorcode: " + error.code +
"Errormessage: "+ error.message );
}
html:the html page is as follows:
<!DOCTYPE html>
<html ng-app>
<head>
<link rel="stylesheet" href="style.css">
<!--<link rel="stylesheet" href="bootstrap.css">-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="bootstrap.css">
<!-- Latest compiled and minified JavaScript -->
<script src="angular.min.js"></script>
<script src="cordova.js"></script>
<script src="angular.animate.min.js"></script>
<script src="angular.route.min.js"></script>
<link rel="stylesheet" href="font-awesome.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
</body>
<script type="text/javascript" src="pro.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>
This code works for me. Hope will help you.
newMapForGuest: function()
{
// setting here default latitude and longitude in case geolocation does not work.
var defaultLatLng = new google.maps.LatLng(1.290, 103.851);
if ( navigator.geolocation )
{
function success(pos) // function will call on success
{
alert('Latitude: '+ pos.coords.latitude +' Longitude: '+pos.coords.longitude);
}
function fail(error) // function will call on fail
{
alert('error message: ' +error);
}
// intializing geolocation to get current position
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 10000});
}
else
{
// in case geolocation does not work then call code mentioned here.
}
},

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

Categories