Retrieving data from Firebase (web) not working - javascript

I just got into Firebase and I´m trying to retrieve data from the realtime database, but I can't get anything to show up on the webpage.
This is what I got, before the JS I got the initialize Firebase code. (IF I delete the val() I receive [object Object] so something is at least working).
JS:
var heading = document.getElementById("head");
var firebaseHeadingRef = firebase.database().ref().child("Heading");
firebaseHeadingRef.on('value', function(datasnapshot) {
heading.innerText = datasnapshot.val();
});
HTML:
<div id="table_body"> <h1 id="head">Some Text</h1>
This is a screenshot from the database:
I appreciate all help :)

The Realtime Database is case sensitive. In your DB screenshot you have Heading but your JS code has .child('heading'). Try making those the same case and it should work. Note that you must also have appropriate Security Rules to allow access for unauthenticated users.

I sort of faced a similar issue, everything was fine including the database rules but no data was being fetched.
My solution
My configuration containing the apiKey & projectId was missing the databaseURL portion, so I recopied the correct configuration & it worked.
P.S
Try checking your console for any warnings from Firebase

Related

How to orderBy with Firebase and Javascript?

I'm trying to get data from Firebase Realtime Database with Javascript and order it by child's value.
I get the data, and limiting it works, but the order does not change.
Here is what I've tried:
var ref = database.ref('users').orderByChild('score').limitToLast(10);
Then I made score key with ".indexOn": "score" on firebase. Then I tried the following.
var ref = database.ref('users').orderByKey().limitToLast(10);[enter image description here][1]
I don't understand where I'm going wrong. I would really appreciate help!
Picture of firebase included!
firebase
It turned out that I had data in wrong format in firebase.
I had saved the score information as string so that's why orderBy did not give the wanted results.
After I changed the data in firebase the query worked just fine!

Knex.js migration issue: Fails with ` relation "knex_migrations" does not exist`

I've been using knex.js successfully for a while now on this project, first time I've come accross this. I deleted all my migration files and dropped my db (locally) and instead used pg_dump to get the DDL and all data from my prod database (not including knex_migrations or knex_migrations_lock tables).
I created a new migration script and used knex.raw to paste all the SQL in. When I ran the migration script, I get the following:
error: insert into "knex_migrations" ("batch", "migration_time", "name") values ($1, $2, $3) - relation "knex_migrations" does not exist
This migration script is being run on a brand new database. When I change what's in the script to just be basic DDL, it works fine. So something about the result of pg_dump and trying to run it using knex is causing it to bomb out.
This isn't a ton of data either really, so I'm not too sure where I'm going wrong - knex is responsible for creating the migration tables and I've made sure there's no mention of knex or migration tables in the DDL.
Any suggestions would be greatly appreciated :)
The table knex_migrations and knex_migrations_lock will be created on running the command
knex migrate:make <name of migration>
Could you please confirm you have executed above knex command.
Once that is done running
knex migrate:latest
should create all schema you have mention. knex.raw
Using pd_dump to dump a database to an sql file, there occurs some additional lines in the beginning of the sql such as:
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
comment those out and the migration should work. You can uncomment one statement at a time to see which one is causing the problem.
I just went down this hole. The following line is the culprit.
SELECT pg_catalog.set_config('search_path', '', false);
It's removing your search path so knex doesn't know where to find anything.

Can you help a beginner troubleshoot setting up firebase database for javscript?

Can I get a little help configuring firebase for a simple card catalog object lesson project? All the walk-throughs I found out there seemed to be beyond my ability until I found this https://deanhume.github.io/firebase-example/ and the code here https://github.com/deanhume/firebase-example/blob/master/no-auth.html
So I understand firebase can save my objects into an array with a URL as this code shows:
var messagesRef = new Firebase('https://brilliant-fire-3159.firebaseio.com');
var messageField = document.getElementById('messageInput');
var messageResults = document.getElementById('results');
function savedata(){
var message = messageField.value;
messagesRef.push({fieldName:'messageField', text:message});
messageField.value = '';}
But I think something's going awry with with my Firebase SDK snippet. I have the URL "firebaseio.com" that's used to store the array, but I think I'm doing something wrong on initializing.
When I use the Config code, I get this error message
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
When I use the CDN code, I get helpers.ts:72 GET https://www.googletagmanager.com/gtag/js?l=dataLayer net::ERR_BLOCKED_BY_CLIENT
And when I use Automatic, I get
GET http://127.0.0.1:5501/__/firebase/7.17.1/firebase-app.js net::ERR_ABORTED 404 (Not Found)
index.html:39 GET http://127.0.0.1:5501/__/firebase/7.17.1/firebase-analytics.js net::ERR_ABORTED 404 (Not Found)
index.html:42 GET http://127.0.0.1:5501/__/firebase/init.js net::ERR_ABORTED 404 (Not Found)
In my JS file, I put in this code:
let firebaseArray = new Firebase('https://project-library-aa3e2.firebaseio.com');
and then simply something like
let title = document.querySelector("#title").value;
let fname = document.querySelector("#fname").value;
let lname = document.querySelector("#lname").value;
let pubDate = document.querySelector("#pubDate").value;
let pages = document.querySelector("#pages").value;
let read = document.getElementById("read").checked;
var addBook = new Book(title, fname, lname, pubDate, pages, read);
myLibrary.push(addBook);
FirebaseArray.push(addBook);
But in my html, I can't find something like this from my firebase dashboard: <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
So I added as the firebase site recommended:
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/7.17.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="/__/firebase/7.17.1/firebase-analytics.js"></script>
<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>
Where am I going wrong? How do I fix it?
This version of the Firebase Realtime Database SDK is very very old and no longer supported:
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
And so is this code:
var messagesRef = new Firebase('https://brilliant-fire-3159.firebaseio.com');
Nothing you see in today's documentation is going to work with the stuff above.
The first thing you should do is stop using this old code, and start over using the documentation. The new APIs are similar, but you should really abandon what you have now, and try to port it to the modern SDKs.
woo hoo, it took me forever to unravel this, but I got some of it down.
Using this basic tutorial helped, even though it's from an earlier version of firebase:
https://techtrench.org/firebase-contact-form/
The steps are basically the same, except that instead of something as simple as
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase.js"></script> before the closing tag, initializing Firebase takes a lot more code.
It's the stuff that you get when you start a project: Copy and paste these scripts into the bottom of your <body> tag, but before you use any Firebase services:
One crucial step that I didn't see in documentation but was mentioned here was "switch to Real-time Database at the top, click Rules, change them to true, true and publish your changes."
Finally, by comparing the code provided in the tutorial with what I did, i realized I could not just do this to initialize:
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
I needed to tell it the product I wanted to use, so:
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-database.js"></script>

Need helping retrieving data from Firebase

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});

can not get data with MysqlSubscription of numtel:mysql for meteor

I am using meteor to do full stack javascript work.And I want to use mysql instead of mongodb.I find numtel:mysql on github, which is a Reactive MySQL for Meteor.
On the server side
Meteor.publish('test', function(){
let array = liveDb.select(
'select * from tasks',
[ { table: 'tasks' } ]
);
console.log('publish test mysql')
console.log(array);
return array;
});
on the client side
let mysqlData = new MysqlSubscription('test');
console.log('subscribe mysql data at client');
console.log(mysqlData);
console.log(mysqlData.length);
console.log(mysqlData.subscriptionId);
console.log(mysqlData[0]);
console.log(mysqlData[1]);
However, I can not get data on the client.And there is a strange phenomenon.From the logs, I find data of mysqlData.However, mysqlData.length is 0, mysqlData[0] and mysqlData[1] are undefined.
Who can help me?
You might want to call mysqlData.reactive() and check if it is ready by using mysqlData.ready() first.
In case the subscription does not work (it does not update the data automatically), you should make sure that you config your MySQL server correctly following the installation instruction.
For me, I could not make it work when I used capital letter on the database name, you should check it also.

Categories